﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Configuration;

using Eforcity.Common35;
using Eforcity.Data.Common35;
using Eforcity.EbayApiDb;
using Eforcity.EbayApiDb.DbTypes;
using Eforcity.EbayApi.Ebay.TradingApi.Webservice;

namespace Eforcity.EbayApi
{
    public partial class EbayTradingApi : IDisposable
    {
        #region  No User Nike
        public List<ActiveListingSalesType> GetSellerEvents(int sellerId, DateTime modUTCTimeFrom, DateTime modUTCTimeTo, out bool needReduceTime)
        {
            string apiName = "GetSellerEvents";
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetSellerEventsRequestType getSellerEventsRequset = new GetSellerEventsRequestType();
            getSellerEventsRequset.Version = _Credentials.Version.ToString();
            getSellerEventsRequset.UserID = EbaySellerData.GetEbaySellerName(sellerId, _EbayStatConn);
            getSellerEventsRequset.ModTimeFrom = modUTCTimeFrom;//OVERLAP
            getSellerEventsRequset.ModTimeFromSpecified = true;
            getSellerEventsRequset.ModTimeTo = modUTCTimeTo;
            getSellerEventsRequset.ModTimeToSpecified = true;
            getSellerEventsRequset.DetailLevel = new DetailLevelCodeType[] { DetailLevelCodeType.ReturnAll };

            GetSellerEventsResponseType response = null;
            List<ActiveListingSalesType> activeListingSalesList = new List<ActiveListingSalesType>();

            try
            {
                UpdateSessionCallCount();
                response = service.GetSellerEvents(getSellerEventsRequset);

                if (response.Ack == AckCodeType.Success)
                {
                    if (response.ItemArray.Length > 0)
                    {
                        foreach (ItemType item in response.ItemArray)
                        {
                            ActiveListingSalesType activeListingSales = new ActiveListingSalesType();
                            activeListingSales.ItemId = ConvertUtility.ToInt64(item.ItemID);
                            activeListingSales.SellerId = sellerId;
                            activeListingSales.QtySold = item.SellingStatus.QuantitySold;
                            if (item.Quantity == 0)
                            {//For this call ,Quantity only return more than 1;
                                activeListingSales.AvailableQty = 1 - activeListingSales.QtySold;
                            }
                            else
                            {
                                activeListingSales.AvailableQty = item.Quantity - activeListingSales.QtySold;
                            }
                            activeListingSales.Price = ConvertUtility.ToDecimal(item.SellingStatus.CurrentPrice.Value);
                            //activeListingSales.ListingType = GetListingTypeId(item.ListingType.ToString());

                            activeListingSalesList.Add(activeListingSales);
                        }
                    }
                }
                else
                {
                    bool hasExceedError = false;
                    foreach (ErrorType errType in response.Errors)
                    {
                        EbayErrorData.InsertErrorGetSellerEvents(sellerId, modUTCTimeFrom, modUTCTimeTo,
                            EbayErrorTypeEnum.ApiLevel, ConvertUtility.ToInt(errType.ErrorCode), errType.LongMessage, _EbayStatConn);

                        if (errType.ErrorCode == "21" || errType.ErrorCode == "904")
                        {
                            EbaySellerData.UpdateSellerStatus(sellerId, false, true, _EbayStatConn);
                        }
                        if (errType.ErrorCode == "21917062")
                        {
                            hasExceedError = true;
                        }
                    }
                    needReduceTime = hasExceedError;
                    return null;
                }
            }
            catch (Exception ex)
            {
                EbayErrorData.InsertErrorGetSellerEvents(sellerId, modUTCTimeFrom, modUTCTimeTo,
                            EbayErrorTypeEnum.SysLevel, -1, ex.ToString(), _EbayStatConn);
                needReduceTime = false;
                return null;
            }
            needReduceTime = false;
            return activeListingSalesList;
        }

        public List<EbayItemBiddersType> GetAllBidders(List<long> itemIdList, BackgroundWorker bw)
        {
            string apiName = "GetAllBidders";

            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            List<EbayItemBiddersType> ebayItemBiddersList = new List<EbayItemBiddersType>();

            //Get All Bidder Request
            GetAllBiddersRequestType getAllBidderRequest = new GetAllBiddersRequestType();
            getAllBidderRequest.Version = _Credentials.Version.ToString();
            DetailLevelCodeType[] dvt = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnAll };
            getAllBidderRequest.DetailLevel = dvt;
            getAllBidderRequest.ErrorHandling = ErrorHandlingCodeType.BestEffort;
            getAllBidderRequest.ErrorHandlingSpecified = true;
            getAllBidderRequest.CallModeSpecified = true;
            getAllBidderRequest.CallMode = GetAllBiddersModeCodeType.ViewAll; // See What we have to take here
            getAllBidderRequest.IncludeBiddingSummary = true;
            getAllBidderRequest.IncludeBiddingSummarySpecified = true;

            foreach (Int64 itemId in itemIdList)
            {
                if (itemId != 0)
                {
                    GetAllBiddersResponseType response = null;
                    getAllBidderRequest.ItemID = itemId.ToString();
                    int retryCount = 0;
                    while (retryCount <= _ApiMaxRetry)
                    {
                        try
                        {
                            //Must have a count update before anycall
                            UpdateSessionCallCount(apiName, ref service);
                            response = service.GetAllBidders(getAllBidderRequest);
                            break;
                        }
                        catch (Exception ex)
                        {
                            //=========================
                            //RESPONSE ERROR (SYS LEVEL)
                            //=========================
                            EbayErrorData.InsertErrorGetAllBidders(itemId, EbayErrorTypeEnum.SysLevel, -1, ex.Message, _EbayStatConn);
                            EbayBidderData.InsertRetryLogGetAllBidders(itemId, _EbayStatConn);

                            //Sleep
                            System.Threading.Thread.Sleep(_RetrySleepTime);
                            retryCount++;
                            //Break  
                            if (retryCount > _ApiMaxRetry)
                            {
                                break;
                            }
                        }
                    }
                    if (response == null)
                    {
                        continue;
                    }
                    //=========================
                    //RESPONSE ERROR (APP LEVEL)
                    //=========================
                    if (response.Errors != null)
                    {
                        int errCode = 0;
                        foreach (ErrorType errType in response.Errors)
                        {
                            errCode = 0;
                            errCode = ConvertUtility.ToInt(errType.ErrorCode);
                            EbayErrorData.InsertErrorGetAllBidders(itemId, EbayErrorTypeEnum.ApiLevel, errCode, errType.LongMessage, _EbayStatConn);
                        }
                        if (errCode == 947)
                        {
                            int errorCount = EbayErrorData.GetErrorGetAllBiddersCount(itemId, errCode, _EbayStatConn);
                            if (errorCount > 10)
                            {
                                EbayListingData.UpdateListingWithGTCStatus(itemId, EbayListingStatusEnum.EbayDeleted, _EbayStatConn);
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                    if (response.BidArray == null)
                    {
                        EbayErrorData.InsertErrorGetAllBidders(itemId, EbayErrorTypeEnum.ApiLevel, -1, "Response.BidArray = null", _EbayStatConn);
                        continue;
                    }

                    if (response.BidArray != null)
                    {
                        if (response.BidArray.Length > 0)
                        {
                            List<EbayBidderType> ebayBidderList = new List<EbayBidderType>();

                            int bidIdx = 0;
                            foreach (OfferType offerType in response.BidArray)
                            {
                                EbayBidderType bidderItem = new EbayBidderType();
                                bidderItem.ItemId = itemId;
                                bidderItem.BidIdx = bidIdx;
                                bidderItem.BidderId = offerType.User.UserID;
                                bidderItem.BidQty = offerType.Quantity;
                                bidderItem.BidPrice = ConvertUtility.ToDecimal(offerType.MaxBid.Value);
                                bidderItem.BidCurrency = GetCurrencyId(ConvertUtility.Trim(offerType.MaxBid.currencyID));
                                bidderItem.ConvertedBidPrice = ConvertUtility.ToDecimal(offerType.ConvertedPrice.Value);
                                bidderItem.Bidtime = offerType.TimeBid;
                                bidderItem.BidAction = GetBidActionId(offerType.Action.ToString());

                                ebayBidderList.Add(bidderItem);
                                bidIdx++;
                            }

                            EbayItemBiddersType ebayItemBidders = new EbayItemBiddersType();
                            ebayItemBidders.ItemId = itemId;
                            ebayItemBidders.EbayBidderList = ebayBidderList;
                            ebayItemBiddersList.Add(ebayItemBidders);
                        }
                        else
                        {
                            //No Bidder
                            EbayItemBiddersType ebayItemBidders = new EbayItemBiddersType();
                            ebayItemBidders.ItemId = itemId;
                            ebayItemBidders.EbayBidderList = new List<EbayBidderType>();
                            ebayItemBiddersList.Add(ebayItemBidders);
                        }
                    }
                }
            }

            return ebayItemBiddersList;

        }

        public bool ReviseItemPrice(long itemId, string currencyCode, double itemPrice)
        {
            string apiName = "ReviseItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            ReviseItemRequestType reviseItemRequest = new ReviseItemRequestType();
            reviseItemRequest.Version = _Credentials.Version.ToString();

            ItemType item = new ItemType();
            item.ItemID = ConvertUtility.Trim(itemId);

            AmountType startPrice = new AmountType();
            try
            {
                startPrice.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
            }
            catch (Exception ex)
            {
                //Use ApiReviseItemQtyError to log error (item will only revise either qty or promoPrice)
                EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);
                return false;
            }
            startPrice.Value = itemPrice;
            item.StartPrice = startPrice;

            reviseItemRequest.Item = item;

            ReviseItemResponseType response = null;
            int retryCount = 0;
            while (retryCount <= _ApiMaxRetry)
            {
                try
                {
                    //Must have a count update before anycall
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.ReviseItem(reviseItemRequest);
                    break;
                }
                catch (Exception ex)
                {
                    //=========================
                    //RESPONSE ERROR (SYS LEVEL)
                    //=========================
                    EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);

                    //Sleep
                    System.Threading.Thread.Sleep(_RetrySleepTime);
                    //Break  
                    retryCount++;
                    if (retryCount > _ApiMaxRetry)
                    {
                        return false;
                    }
                }
            }
            //=========================
            //RESPONSE ERROR (SYS LEVEL)
            //=========================
            if (response == null)
            {
                string err = "Response is null.";
                EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.SysLevel, err, _EbayStatConn);
                return false;
            }

            //Revise Success
            if (response.Ack == AckCodeType.Success)
            {
                return true;
            }
            else
            {
                //=========================
                //RESPONSE ERROR (APP LEVEL)
                //=========================
                string err = response.Ack.ToString() + ": ";
                if (response.Errors != null)
                {
                    foreach (ErrorType errType in response.Errors)
                    {
                        err += errType.LongMessage;
                    }
                    int maxLen = 5000;
                    if (err.Length > maxLen)
                    {
                        err = err.Remove(maxLen);
                    }
                }
                else
                {
                    err += ConvertUtility.Trim(response.Message);
                }
                EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.ApiLevel, err, _EbayStatConn);
                if (response.Ack == AckCodeType.Warning)
                {
                    //Request processing completed with warning information being included in the response message
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        public bool ReviseItemQtyPrice(long itemId, int itemQty, string currencyCode, double itemPrice, out string respErrMsg)
        {
            respErrMsg = string.Empty;

            string apiName = "ReviseItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            ReviseItemRequestType reviseItemRequest = new ReviseItemRequestType();
            reviseItemRequest.Version = _Credentials.Version.ToString();

            ItemType item = new ItemType();
            item.ItemID = ConvertUtility.Trim(itemId);
            item.Quantity = itemQty;
            item.QuantitySpecified = itemQty > 0;

            if (itemPrice > 0)
            {
                AmountType startPrice = new AmountType();
                try
                {
                    startPrice.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
                }
                catch (Exception ex)
                {
                    //Use ApiReviseItemQtyError to log error (item will only revise either qty or promoPrice)
                    EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);
                    return false;
                }
                startPrice.Value = itemPrice;
                item.StartPrice = startPrice;
                //item.BuyItNowPrice = 
            }

            reviseItemRequest.Item = item;

            ReviseItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);

                response = service.ReviseItem(reviseItemRequest);

                if (response == null)
                {
                    throw new Exception("Response is null.");
                }
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);
                //Break  
                return false;
            }

            //Revise Success
            if (response.Ack == AckCodeType.Success)
            {
                return true;
            }
            else
            {
                //=========================
                //RESPONSE ERROR (APP LEVEL)
                //=========================
                string err = response.Ack.ToString() + ": ";
                if (response.Errors != null)
                {
                    foreach (ErrorType errType in response.Errors)
                    {
                        //Auction ended, You are not allowed to revise ended auctions.
                        respErrMsg += errType.ShortMessage;
                        if (errType.ErrorCode == "291")
                        {
                            //Log the item, next time not run
                            EbayReviseItemData.InsertReviseItemEndListing(itemId, _EbayStatConn);
                        }
                        else
                        {
                            EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.ApiLevel, errType.LongMessage, _EbayStatConn);
                        }
                    }
                }
                if (response.Ack == AckCodeType.Warning)
                {
                    //Request processing completed with warning information being included in the response message
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public bool ReviseItemQtyPrice(long itemId, int itemQty,
            string currencyCode, double startPrice, double binPrice, out string respErrMsg)
        {
            respErrMsg = string.Empty;

            string apiName = "ReviseItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            ReviseItemRequestType reviseItemRequest = new ReviseItemRequestType();
            reviseItemRequest.Version = _Credentials.Version.ToString();

            ItemType item = new ItemType();
            item.ItemID = ConvertUtility.Trim(itemId);
            item.Quantity = itemQty;
            item.QuantitySpecified = itemQty > 0;

            if (startPrice > 0)
            {
                AmountType startPriceType = new AmountType();
                try
                {
                    startPriceType.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
                }
                catch (Exception ex)
                {
                    //Use ApiReviseItemQtyError to log error (item will only revise either qty or promoPrice)
                    EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);
                    return false;
                }
                startPriceType.Value = startPrice;
                item.StartPrice = startPriceType;
            }

            if (binPrice > 0)
            {
                AmountType binPriceType = new AmountType();
                try
                {
                    binPriceType.currencyID = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), currencyCode);
                }
                catch (Exception ex)
                {
                    //Use ApiReviseItemQtyError to log error (item will only revise either qty or promoPrice)
                    EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);
                    return false;
                }
                binPriceType.Value = binPrice;
                item.BuyItNowPrice = binPriceType;
            }

            reviseItemRequest.Item = item;

            ReviseItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);

                response = service.ReviseItem(reviseItemRequest);

                if (response == null)
                {
                    throw new Exception("Response is null.");
                }
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);
                //Break  
                return false;
            }

            //Revise Success
            if (response.Ack == AckCodeType.Success)
            {
                return true;
            }
            else
            {
                //=========================
                //RESPONSE ERROR (APP LEVEL)
                //=========================
                string err = response.Ack.ToString() + ": ";
                if (response.Errors != null)
                {
                    foreach (ErrorType errType in response.Errors)
                    {
                        //Auction ended, You are not allowed to revise ended auctions.
                        respErrMsg += errType.ShortMessage;
                        if (errType.ErrorCode == "291")
                        {
                            //Log the item, next time not run
                            EbayReviseItemData.InsertReviseItemEndListing(itemId, _EbayStatConn);
                        }
                        else
                        {
                            EbayErrorData.InsertErrorReviseItemPrice(itemId, EbayErrorTypeEnum.ApiLevel, errType.LongMessage, _EbayStatConn);
                        }
                    }
                }
                if (response.Ack == AckCodeType.Warning)
                {
                    //Request processing completed with warning information being included in the response message
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }


        public AttributeSetType[] GetItem(long itemId)
        {
            string apiName = "GetItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetItemRequestType getitemRequest = new GetItemRequestType();

            DetailLevelCodeType[] dvt = new DetailLevelCodeType[1] { DetailLevelCodeType.ItemReturnAttributes };
            getitemRequest.DetailLevel = dvt;
            getitemRequest.ItemID = ConvertUtility.Trim(itemId);
            getitemRequest.IncludeItemSpecificsSpecified = true;
            getitemRequest.IncludeItemSpecifics = true;

            getitemRequest.Version = _Credentials.Version.ToString();

            GetItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetItem(getitemRequest);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorGetItem(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                return null;
            }

            if (response.Errors != null)
            {
                foreach (ErrorType errType in response.Errors)
                {
                    EbayErrorData.InsertErrorGetItem(itemId, EbayErrorTypeEnum.ApiLevel, errType.LongMessage, _EbayStatConn);
                }
                return null;
            }
            return response.Item.AttributeSetArray;
        }





        public void GetSellerTransactions(int entriesPerPage, int hourProcessLot, Action<string> trace)
        {
            string apiName = "GetSellerTransactions";

            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            GetSellerTransactionsRequestType request = new GetSellerTransactionsRequestType();
            request.Version = _Credentials.Version.ToString();
            DetailLevelCodeType[] dvt = new DetailLevelCodeType[1] { DetailLevelCodeType.ItemReturnDescription };
            request.DetailLevel = dvt;
            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.EntriesPerPage = entriesPerPage;
            request.Pagination.PageNumberSpecified = true;
            GetSellerTransactionsResponseType response = null;

            string sellerName = EbaySellerData.GetEbaySellerName(_Credentials.SellerId, _EbayStatConn);

            DateTime dateTimeFrom = EbayTransactionData.GetLastProcStartDate(_Credentials.SellerId, _EbayStatConn);
            dateTimeFrom = dateTimeFrom.AddHours(-hourProcessLot);//warp time
            DateTime dateTimeTo = dateTimeFrom.AddHours(hourProcessLot);
            while (dateTimeTo < DateTime.Now.ToUniversalTime())
            {
                request.ModTimeFrom = dateTimeFrom;
                request.ModTimeFromSpecified = true;
                request.ModTimeTo = dateTimeTo;
                request.ModTimeToSpecified = true;
                if (trace != null)
                {
                    trace("Processing " + sellerName + " Transactions \n\r DateTime(UTC)\tFrom\t" + dateTimeFrom.ToString("yyyy-MM-dd HH:mm:ss") + "\tTo\t" + dateTimeTo.ToString("yyyy-MM-dd HH:mm:ss"));
                }

                int initTotalEntries = 0;
                int initTotalPage = 0;
                int currentTotalEntries = 0;
                int currentTotalPage = 0;
                int currentPageNumber = 1;
                bool finished = false;
                do
                {
                    if (trace != null)
                    {
                        trace("\tCurrent page: " + currentPageNumber);
                    }
                    try
                    {
                        request.Pagination.PageNumber = currentPageNumber;
                        UpdateSessionCallCount(apiName, ref service);
                        int retryCount = 0;
                        while (retryCount <= _ApiMaxRetry)
                        {
                            try
                            {
                                response = service.GetSellerTransactions(request);
                                break;
                            }
                            catch (Exception ex)
                            {
                                retryCount++;
                                EbayErrorData.InsertErrorGetSellerTransactions(_Credentials.SellerId, dateTimeFrom, dateTimeTo, -1, -1, EbayErrorTypeEnum.SysLevel, -1, ex.Message, _EbayStatConn);
                                trace("\t" + ex.Message);
                                System.Threading.Thread.Sleep(_RetrySleepTime);
                            }
                        }
                        if (response == null)
                        {
                            System.Threading.Thread.Sleep(60 * 1000);
                            continue;//do
                        }
                        if (response.Ack == AckCodeType.Success)
                        {
                            if (currentPageNumber == 1)
                            {
                                initTotalPage = response.PaginationResult.TotalNumberOfPages;
                                initTotalEntries = response.PaginationResult.TotalNumberOfEntries;
                            }
                            currentTotalPage = response.PaginationResult.TotalNumberOfPages;
                            currentTotalEntries = response.PaginationResult.TotalNumberOfEntries;

                            if (response.TransactionArray != null)
                            {
                                List<EbayTransactionType> transactionList = new List<EbayTransactionType>();
                                EbayTransactionType transDbType = null;
                                foreach (TransactionType trans in response.TransactionArray)
                                {
                                    transDbType = new EbayTransactionType();
                                    transDbType.TransactionID = Convert.ToInt64(trans.TransactionID);
                                    if (trans.Status != null)
                                    {
                                        if (!_CompleteStatusCodeTypeDict.ContainsKey(trans.Status.CompleteStatus.ToString()))
                                        {
                                            EbayCodeTypeData.InsertCompleteStatusCodeType(Convert.ToByte(trans.Status.CompleteStatus.ToString("D")), trans.Status.CompleteStatus.ToString(), _EbayStatConn);
                                            //Renew 
                                            _CompleteStatusCodeTypeDict = EbayCodeTypeData.GetCompleteStatusCodeTypeDict(_EbayStatConn);

                                        }
                                        transDbType.CompleteStatusId = _CompleteStatusCodeTypeDict[trans.Status.CompleteStatus.ToString()];
                                        if (!_CheckOutStatusCodeTypeDict.ContainsKey(trans.Status.CheckoutStatus.ToString()))
                                        {
                                            //Renew 
                                            EbayCodeTypeData.InsertCheckOutStatusCodeType(Convert.ToByte(trans.Status.CheckoutStatus.ToString("D")), trans.Status.CheckoutStatus.ToString(), _EbayStatConn);
                                            _CheckOutStatusCodeTypeDict = EbayCodeTypeData.GetCheckOutStatusCodeTypeDict(_EbayStatConn);
                                        }
                                        transDbType.CheckoutStatusId = _CheckOutStatusCodeTypeDict[trans.Status.CheckoutStatus.ToString()];
                                        if (!_PaymentStatucCodeTypeDict.ContainsKey(trans.Status.eBayPaymentStatus.ToString()))
                                        {
                                            //Renew 
                                            EbayCodeTypeData.InsertPaymentStatusCodeType(Convert.ToByte(trans.Status.eBayPaymentStatus.ToString("D")), trans.Status.eBayPaymentStatus.ToString(), _EbayStatConn);
                                            _PaymentStatucCodeTypeDict = EbayCodeTypeData.GetPaymentStatusCodeTypeDict(_EbayStatConn);
                                        }
                                        transDbType.PaymentStatusId = _PaymentStatucCodeTypeDict[trans.Status.eBayPaymentStatus.ToString()];

                                        if (trans.Status.LastTimeModified != null)
                                        {
                                            transDbType.LastTimeModified = trans.Status.LastTimeModified;
                                        }
                                    }
                                    transDbType.ItemId = Int64.Parse(trans.Item.ItemID);
                                    transDbType.CreatedDate = trans.CreatedDate;
                                    transDbType.QuantityPurchased = trans.QuantityPurchased;
                                    transactionList.Add(transDbType);

                                }
                                EbayTransactionData.InsertTransactions(transactionList, _EbayStatConn);
                            }
                            #region next page
                            if (currentPageNumber >= response.PaginationResult.TotalNumberOfPages)
                            {
                                finished = true;
                            }
                            else
                            {
                                currentPageNumber++;
                            }
                            #endregion
                        }//success
                        else
                        {
                            foreach (ErrorType err in response.Errors)
                            {
                                string errMsg = err.LongMessage;
                                if (err.ErrorCode == "340")
                                {
                                    //Page number is out of range.
                                    errMsg += "CurrentPage:" + currentPageNumber
                                        + " LastTotalPage:" + currentTotalPage + " LastTotalEntries:" + currentTotalEntries
                                        + " InitTotalPage:" + initTotalPage + " InitTotalEntries:" + initTotalEntries;
                                    //By Pass
                                    finished = true;
                                }
                                EbayErrorData.InsertErrorGetSellerTransactions(_Credentials.SellerId, dateTimeFrom, dateTimeTo, entriesPerPage, currentPageNumber, EbayErrorTypeEnum.ApiLevel, Convert.ToInt32(err.ErrorCode), errMsg, _EbayStatConn);
                            }
                            System.Threading.Thread.Sleep(60 * 1000);
                        }//fail
                    }
                    catch (Exception ex)
                    {
                        EbayErrorData.InsertErrorGetSellerTransactions(_Credentials.SellerId, dateTimeFrom, dateTimeTo, -1, -1, EbayErrorTypeEnum.SysLevel, -1, ex.Message, _EbayStatConn);
                        trace("\tError:" + ex.Message);
                        System.Threading.Thread.Sleep(60 * 1000);
                    }
                } while (!finished);
                EbayTransactionData.InsertProcHistSellerTransactions(_Credentials.SellerId, dateTimeTo, _EbayStatConn);
                dateTimeFrom = dateTimeTo;
                dateTimeTo = dateTimeFrom.AddHours(hourProcessLot);
            }
        }

        public List<EbayFeedbackType> GetFeedback(int sellerId, string ebaySellerName, int entriesPerPage, int pageNumber)
        {
            string apiName = "GetFeedback";

            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetFeedbackRequestType request = new GetFeedbackRequestType();
            request.Version = _Credentials.Version.ToString();

            DetailLevelCodeType[] dvt = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnAll };
            request.DetailLevel = dvt;
            request.UserID = ebaySellerName;
            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.EntriesPerPage = entriesPerPage;
            request.Pagination.PageNumberSpecified = true;
            request.Pagination.PageNumber = pageNumber;

            GetFeedbackResponseType response;

            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetFeedback(request);
               
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                //Need a table to store

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                return null;
            }

            //=========================
            //RESPONSE ERROR (APP LEVEL)
            //=========================
            if (response.Errors != null)
            {
                foreach (ErrorType errType in response.Errors)
                {
                    //Need a table to store
                }
                return null;
            }

            List<EbayFeedbackType> ebayFeedbackList = new List<EbayFeedbackType>();
            //Buld the list and return
            if (response.FeedbackDetailArray != null)
            {
                foreach (FeedbackDetailType feedbackDetail in response.FeedbackDetailArray)
                {
                    EbayFeedbackType ebayFeedback = new EbayFeedbackType();
                    ebayFeedback.CommentingUser = ConvertUtility.Trim(feedbackDetail.CommentingUser);
                    ebayFeedback.CommentText = ConvertUtility.Trim(feedbackDetail.CommentText);
                    ebayFeedback.CommentTime = feedbackDetail.CommentTime;

                    if (_CommentTypeCodeTypeDict.ContainsKey(ConvertUtility.Trim(feedbackDetail.CommentType)))
                    {
                        ebayFeedback.CommentType = _CommentTypeCodeTypeDict[ConvertUtility.Trim(feedbackDetail.CommentType)];
                    }
                    else
                    {
                        ebayFeedback.CommentType = 0;
                    }

                    ebayFeedback.FeedbackId = ConvertUtility.ToInt64(feedbackDetail.FeedbackID);
                    ebayFeedback.ItemId = ConvertUtility.ToInt64(feedbackDetail.ItemID);
                    ebayFeedback.TransactionId = ConvertUtility.ToInt64(feedbackDetail.TransactionID);
                    ebayFeedback.SellerId = sellerId;
                    ebayFeedbackList.Add(ebayFeedback);
                }
            }
            else
            {
                return null;
            }
            return ebayFeedbackList;
        }
        public Dictionary<int, EbayFeedbackSummaryType> GetFeedbackSummary(int sellerId, string ebaySellerName)
        {
            string apiName = "GetFeedback";

            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetFeedbackRequestType request = new GetFeedbackRequestType();
            request.Version = _Credentials.Version.ToString();

            DetailLevelCodeType[] dvt = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnSummary };
            request.DetailLevel = dvt;
            request.UserID = ebaySellerName;
            GetFeedbackResponseType response;

            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetFeedback(request);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                //Need a table to store

                //Sleep
                System.Threading.Thread.Sleep(5000);//5000
                //Break  
                return null;
            }

            //=========================
            //RESPONSE ERROR (APP LEVEL)
            //=========================
            if (response.Errors != null)
            {
                foreach (ErrorType errType in response.Errors)
                {
                    //Need a table to store
                }
                return null;
            }

            Dictionary<int, EbayFeedbackSummaryType> feedbackSummaryDict = new Dictionary<int, EbayFeedbackSummaryType>();
            //Buld the list and return
            if (response.FeedbackSummary != null)
            {
                if (response.FeedbackSummary.TotalFeedbackPeriodArray.Length > 0)//Total Comment
                {
                    foreach (FeedbackPeriodType feedbackPeriodType in response.FeedbackSummary.TotalFeedbackPeriodArray)
                    {
                        if (feedbackPeriodType.PeriodInDays >= 0)
                        {
                            EbayFeedbackSummaryType ebayFeedbackSummaryType = new EbayFeedbackSummaryType();
                            ebayFeedbackSummaryType.SellerId = sellerId;
                            ebayFeedbackSummaryType.TotalScore = feedbackPeriodType.Count;
                            ebayFeedbackSummaryType.PeriodInDays = feedbackPeriodType.PeriodInDays;
                            feedbackSummaryDict.Add(feedbackPeriodType.PeriodInDays, ebayFeedbackSummaryType);//Add
                        }
                    }
                }
                if (response.FeedbackSummary.NegativeFeedbackPeriodArray.Length > 0)//Negative Comment
                {
                    foreach (FeedbackPeriodType feedbackPeriodType in response.FeedbackSummary.NegativeFeedbackPeriodArray)
                    {
                        if (feedbackSummaryDict.ContainsKey(feedbackPeriodType.PeriodInDays))//Exists
                        {
                            feedbackSummaryDict[feedbackPeriodType.PeriodInDays].NegativeScore = feedbackPeriodType.Count;//Update
                        }
                        else
                        {
                            EbayFeedbackSummaryType ebayFeedbackSummaryType = new EbayFeedbackSummaryType();
                            ebayFeedbackSummaryType.SellerId = sellerId;
                            ebayFeedbackSummaryType.NegativeScore = feedbackPeriodType.Count;
                            ebayFeedbackSummaryType.PeriodInDays = feedbackPeriodType.PeriodInDays;
                            feedbackSummaryDict.Add(feedbackPeriodType.PeriodInDays, ebayFeedbackSummaryType);//Add
                        }

                    }
                }
                if (response.FeedbackSummary.NeutralFeedbackPeriodArray.Length > 0)//Neutral Comment
                {
                    foreach (FeedbackPeriodType feedbackPeriodType in response.FeedbackSummary.NeutralFeedbackPeriodArray)
                    {
                        if (feedbackPeriodType.PeriodInDays >= 0)
                        {
                            if (feedbackSummaryDict.ContainsKey(feedbackPeriodType.PeriodInDays))//Exists
                            {
                                feedbackSummaryDict[feedbackPeriodType.PeriodInDays].NeutralScore = feedbackPeriodType.Count;//Update
                            }
                            else
                            {
                                EbayFeedbackSummaryType ebayFeedbackSummaryType = new EbayFeedbackSummaryType();
                                ebayFeedbackSummaryType.SellerId = sellerId;
                                ebayFeedbackSummaryType.NeutralScore = feedbackPeriodType.Count;
                                ebayFeedbackSummaryType.PeriodInDays = feedbackPeriodType.PeriodInDays;
                                feedbackSummaryDict.Add(feedbackPeriodType.PeriodInDays, ebayFeedbackSummaryType);//Add
                            }
                        }
                    }
                }
                if (response.FeedbackSummary.PositiveFeedbackPeriodArray.Length > 0)//Positive Comment
                {
                    foreach (FeedbackPeriodType feedbackPeriodType in response.FeedbackSummary.PositiveFeedbackPeriodArray)
                    {
                        if (feedbackPeriodType.PeriodInDays >= 0)
                        {
                            if (feedbackSummaryDict.ContainsKey(feedbackPeriodType.PeriodInDays))//Exists
                            {
                                feedbackSummaryDict[feedbackPeriodType.PeriodInDays].PositiveScore = feedbackPeriodType.Count;//Update
                            }
                            else
                            {
                                EbayFeedbackSummaryType ebayFeedbackSummaryType = new EbayFeedbackSummaryType();
                                ebayFeedbackSummaryType.SellerId = sellerId;
                                ebayFeedbackSummaryType.PositiveScore = feedbackPeriodType.Count;
                                ebayFeedbackSummaryType.PeriodInDays = feedbackPeriodType.PeriodInDays;
                                feedbackSummaryDict.Add(feedbackPeriodType.PeriodInDays, ebayFeedbackSummaryType);//Add
                            }
                        }
                    }
                }
                if (response.FeedbackSummary.SellerRatingSummaryArray.Length > 0)
                {
                    foreach (AverageRatingSummaryType avgRatingSummaryType in response.FeedbackSummary.SellerRatingSummaryArray)
                    {
                        int periodInDays = -1;
                        if (avgRatingSummaryType.FeedbackSummaryPeriod == FeedbackSummaryPeriodCodeType.FiftyTwoWeeks)
                        {
                            periodInDays = 365;
                        }
                        if (avgRatingSummaryType.FeedbackSummaryPeriod == FeedbackSummaryPeriodCodeType.ThirtyDays)
                        {
                            periodInDays = 30;
                        }
                        if (avgRatingSummaryType.FeedbackSummaryPeriod == FeedbackSummaryPeriodCodeType.CustomCode)
                        {
                            continue;
                        }
                        EbayFeedbackSummaryType ebayFeedbackSummaryType = new EbayFeedbackSummaryType();
                        if (feedbackSummaryDict.ContainsKey(periodInDays))
                        {
                            ebayFeedbackSummaryType = feedbackSummaryDict[periodInDays];
                        }
                        else
                        {
                            ebayFeedbackSummaryType.SellerId = sellerId;
                            ebayFeedbackSummaryType.PeriodInDays = periodInDays;
                            feedbackSummaryDict.Add(ebayFeedbackSummaryType.PeriodInDays, ebayFeedbackSummaryType);
                        }
                        foreach (AverageRatingDetailsType avgRatingDetailsType in avgRatingSummaryType.AverageRatingDetails)
                        {

                            if (avgRatingDetailsType.RatingDetail == FeedbackRatingDetailCodeType.ItemAsDescribed)
                            {
                                ebayFeedbackSummaryType.ItemAsDescribedRate = avgRatingDetailsType.Rating;
                                ebayFeedbackSummaryType.ItemAsDescribedScore = avgRatingDetailsType.RatingCount;
                            }
                            if (avgRatingDetailsType.RatingDetail == FeedbackRatingDetailCodeType.Communication)
                            {
                                ebayFeedbackSummaryType.CommunicationRate = avgRatingDetailsType.Rating;
                                ebayFeedbackSummaryType.CommunicationScore = avgRatingDetailsType.RatingCount;
                            }
                            if (avgRatingDetailsType.RatingDetail == FeedbackRatingDetailCodeType.ShippingTime)
                            {
                                ebayFeedbackSummaryType.ShipTimeRate = avgRatingDetailsType.Rating;
                                ebayFeedbackSummaryType.ShipTimeScore = avgRatingDetailsType.RatingCount;
                            }
                            if (avgRatingDetailsType.RatingDetail == FeedbackRatingDetailCodeType.ShippingAndHandlingCharges)
                            {
                                ebayFeedbackSummaryType.ShipAndHdlChargesRate = avgRatingDetailsType.Rating;
                                ebayFeedbackSummaryType.ShipAndHdlChargesScore = avgRatingDetailsType.RatingCount;
                            }
                        }
                        feedbackSummaryDict[periodInDays] = ebayFeedbackSummaryType;
                    }
                }
            }
            else
            {
                return null;
            }
            return feedbackSummaryDict;
        }

        public List<EbayMessageType> GetMemberMessages(int sellerId, DateTime startTimeFrom, DateTime startTimeTo, int entriesPerPage)
        {
            List<EbayMessageType> ebayMemberMessageList = new List<EbayMessageType>();

            string apiName = "GetMemberMessages";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetMemberMessagesRequestType request = new GetMemberMessagesRequestType();
            request.Version = _Credentials.Version.ToString();

            request.MailMessageType = MessageTypeCodeType.All;

            request.MailMessageTypeSpecified = true;
            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPage = entriesPerPage;
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.PageNumberSpecified = true;

            //request.MessageStatus = MessageStatusTypeCodeType.Unanswered;//add by alex 20080715
            //request.MessageStatusSpecified = true; 

            request.StartCreationTime = startTimeFrom;
            request.StartCreationTimeSpecified = true;
            request.EndCreationTime = startTimeTo;
            request.EndCreationTimeSpecified = true;

            //Loop the page
            int pageCounter = 1;
            int retryCount = 0;
            bool finished = false;
            do
            {
                request.Pagination.PageNumber = pageCounter;

                GetMemberMessagesResponseType response;

                try
                {
                    //Must have a count update before anycall
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetMemberMessages(request);
                }
                catch (Exception ex)
                {
                    //=========================
                    //RESPONSE ERROR (SYS LEVEL)
                    //=========================
                    EbayErrorData.InsertErrorGetMemberMessages(sellerId, startTimeFrom, startTimeTo, entriesPerPage,
                            pageCounter, EbayErrorTypeEnum.SysLevel, -1, ex.Message, _EbayStatConn);

                    //Sleep
                    System.Threading.Thread.Sleep(_RetrySleepTime);//5000

                    //Retry or Break                        
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        return null;
                    }
                }

                //=========================
                //RESPONSE ERROR (APP LEVEL)
                //=========================
                if (response.Errors != null)
                {
                    foreach (ErrorType errType in response.Errors)
                    {
                        EbayErrorData.InsertErrorGetMemberMessages(sellerId, startTimeFrom, startTimeTo, entriesPerPage,
                            pageCounter, EbayErrorTypeEnum.ApiLevel, ConvertUtility.ToInt(errType.ErrorCode), errType.LongMessage, _EbayStatConn);
                    }
                    if (response.Errors.Length == 1 && response.Errors[0].ErrorCode == "16202")
                    {
                        //Skip this warning "We did not find your item in our system."
                    }
                    else
                    {
                        //any other errors occur in a process lot means Whole lot fail, and have to retry      
                        return null;
                    }
                }
                if (response.MemberMessage == null)
                {
                    if (response.Ack == AckCodeType.Success
                        && response.HasMoreItems == false
                        && response.PaginationResult.TotalNumberOfEntries == 0)
                    {
                        //No Member Message
                        return ebayMemberMessageList;
                    }
                    else
                    {
                        //Shall be Error
                        return null;
                    }
                }


                //================
                //PROCESS RESPONSE
                //================
                if (response.MemberMessage.Length != 0)
                {
                    //Preform the update here
                    foreach (MemberMessageExchangeType memberMessageType in response.MemberMessage)
                    {

                        EbayMessageType memberMessage = new EbayMessageType();

                        memberMessage.CreationDate = memberMessageType.CreationDate;
                        memberMessage.LastModifiedDate = memberMessageType.LastModifiedDate;
                        memberMessage.MessageStatus = GetMessageStatusTypeId(memberMessageType.MessageStatus.ToString());

                        if (memberMessageType.Question != null)
                        {
                            memberMessage.MessageId = ConvertUtility.ToInt64(memberMessageType.Question.MessageID);
                            memberMessage.ParentMessageID = ConvertUtility.ToInt64(memberMessageType.Question.ParentMessageID);
                            memberMessage.MessageType = GetMessageTypeId(memberMessageType.Question.MessageType.ToString());
                            memberMessage.Subject = memberMessageType.Question.Subject;
                            memberMessage.Body = memberMessageType.Question.Body;
                            memberMessage.QuestionType = GetQuestionTypeId(memberMessageType.Question.QuestionType.ToString());
                            memberMessage.SenderID = memberMessageType.Question.SenderID;
                            if (memberMessageType.Question.RecipientID != null
                                && memberMessageType.Question.RecipientID.Length > 0)
                            {
                                if (memberMessageType.Question.RecipientID.Length == 1)
                                {
                                    memberMessage.RecipientID = memberMessageType.Question.RecipientID[0];
                                }
                                else
                                {
                                    for (int i = 0; i < memberMessageType.Question.RecipientID.Length; i++)
                                    {
                                        memberMessage.RecipientID += memberMessageType.Question.RecipientID[i] + ",";
                                    }
                                }
                            }

                            memberMessage.SenderEmail = memberMessageType.Question.SenderEmail;
                            memberMessage.DisplayToPublic = memberMessageType.Question.DisplayToPublic;
                            memberMessage.EmailCopyToSender = memberMessageType.Question.EmailCopyToSender;
                            memberMessage.HideSendersEmailAddress = memberMessageType.Question.HideSendersEmailAddress;
                        }
                        if (memberMessageType.Item != null)
                        {
                            memberMessage.ItemId = ConvertUtility.ToInt64(memberMessageType.Item.ItemID);
                            if (memberMessageType.Item.ListingDetails != null)
                            {
                                memberMessage.StartTime = memberMessageType.Item.ListingDetails.StartTime;
                                memberMessage.EndTime = memberMessageType.Item.ListingDetails.EndTime;
                            }
                            memberMessage.Title = memberMessageType.Item.Title;

                            if (memberMessageType.Item.SellingStatus != null)
                            {
                                memberMessage.CurrentPrice = memberMessageType.Item.SellingStatus.CurrentPrice.Value;
                            }
                        }
                        memberMessage.SellerId = sellerId;
                        ebayMemberMessageList.Add(memberMessage);
                    }

                    pageCounter++;
                    retryCount = 0;

                    if (pageCounter > response.PaginationResult.TotalNumberOfPages)
                    {
                        //Reach last Page 
                        finished = true;
                    }
                }
                else
                {
                    //Response Contains 0 item
                    finished = true;
                }
            }
            while (!finished);

            return ebayMemberMessageList;
        }
        private List<EbayMessageType> GetMemberMessages(int sellerId, string senderId, MessageStatusTypeCodeType msgSts, DateTime startTimeFrom, int entriesPerPage)
        {
            List<EbayMessageType> ebayMemberMessageList = new List<EbayMessageType>();

            string apiName = "GetMemberMessages";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            
            GetMemberMessagesRequestType request = new GetMemberMessagesRequestType();
            request.Version = _Credentials.Version.ToString();

            request.MailMessageType = MessageTypeCodeType.All;
            request.MailMessageTypeSpecified = true;
            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPage = entriesPerPage;
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.PageNumberSpecified = true;
            if (!string.IsNullOrEmpty(senderId))//messages from the specified sender.
            {
                request.SenderID = senderId;
            }

            if (msgSts != null)
            {
                request.MessageStatus = msgSts;//add by alex 20080715
                request.MessageStatusSpecified = true;
            }
            request.StartCreationTime = startTimeFrom;
            request.StartCreationTimeSpecified = true;

            //Loop the page
            int pageCounter = 1;
            int retryCount = 0;
            bool finished = false;
            do
            {
                request.Pagination.PageNumber = pageCounter;

                GetMemberMessagesResponseType response;
                try
                {
                    //Must have a count update before anycall
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetMemberMessages(request);
                }
                catch (Exception ex)
                {
                    //=========================
                    //RESPONSE ERROR (SYS LEVEL)
                    //=========================
                    EbayErrorData.InsertErrorGetMemberMessages(sellerId, startTimeFrom, DateTime.Now, entriesPerPage,
                            pageCounter, EbayErrorTypeEnum.SysLevel, -1, ex.Message, _EbayStatConn);

                    //Sleep
                    System.Threading.Thread.Sleep(_RetrySleepTime);//5000

                    //Retry or Break                        
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        return null;
                    }
                }

                //=========================
                //RESPONSE ERROR (APP LEVEL)
                //=========================
                if (response.Errors != null)
                {
                    foreach (ErrorType errType in response.Errors)
                    {
                        EbayErrorData.InsertErrorGetMemberMessages(sellerId, startTimeFrom, DateTime.Now, entriesPerPage,
                            pageCounter, EbayErrorTypeEnum.ApiLevel, ConvertUtility.ToInt(errType.ErrorCode), errType.LongMessage, _EbayStatConn);
                    }
                    //any error occur in a process lot means Whole lot fail, and have to retry      
                    return null;
                }
                if (response.MemberMessage == null)
                {
                    if (response.Ack == AckCodeType.Success
                        && response.HasMoreItems == false
                        && response.PaginationResult.TotalNumberOfEntries == 0)
                    {
                        //No Member Message
                        return ebayMemberMessageList;
                    }
                    else
                    {
                        //Shall be Error
                        return null;
                    }
                }


                //================
                //PROCESS RESPONSE
                //================
                if (response.MemberMessage.Length != 0)
                {
                    //Preform the update here
                    foreach (MemberMessageExchangeType memberMessageType in response.MemberMessage)
                    {

                        EbayMessageType memberMessage = new EbayMessageType();

                        memberMessage.CreationDate = memberMessageType.CreationDate;
                        memberMessage.LastModifiedDate = memberMessageType.LastModifiedDate;
                        memberMessage.MessageStatus = GetMessageStatusTypeId(memberMessageType.MessageStatus.ToString());

                        if (memberMessageType.Question != null)
                        {
                            memberMessage.MessageId = ConvertUtility.ToInt64(memberMessageType.Question.MessageID);
                            memberMessage.ParentMessageID = ConvertUtility.ToInt64(memberMessageType.Question.ParentMessageID);
                            memberMessage.MessageType = GetMessageTypeId(memberMessageType.Question.MessageType.ToString());
                            memberMessage.Subject = memberMessageType.Question.Subject;
                            memberMessage.Body = memberMessageType.Question.Body;
                            memberMessage.QuestionType = GetQuestionTypeId(memberMessageType.Question.QuestionType.ToString());
                            memberMessage.SenderID = memberMessageType.Question.SenderID;
                            if (memberMessageType.Question.RecipientID != null
                                && memberMessageType.Question.RecipientID.Length > 0)
                            {
                                if (memberMessageType.Question.RecipientID.Length == 1)
                                {
                                    memberMessage.RecipientID = memberMessageType.Question.RecipientID[0];
                                }
                                else
                                {
                                    for (int i = 0; i < memberMessageType.Question.RecipientID.Length; i++)
                                    {
                                        memberMessage.RecipientID += memberMessageType.Question.RecipientID[i] + ",";
                                    }
                                }
                            }

                            memberMessage.SenderEmail = memberMessageType.Question.SenderEmail;
                            memberMessage.DisplayToPublic = memberMessageType.Question.DisplayToPublic;
                            memberMessage.EmailCopyToSender = memberMessageType.Question.EmailCopyToSender;
                            memberMessage.HideSendersEmailAddress = memberMessageType.Question.HideSendersEmailAddress;
                        }
                        if (memberMessageType.Item != null)
                        {
                            memberMessage.ItemId = ConvertUtility.ToInt64(memberMessageType.Item.ItemID);
                            if (memberMessageType.Item.ListingDetails != null)
                            {
                                memberMessage.StartTime = memberMessageType.Item.ListingDetails.StartTime;
                                memberMessage.EndTime = memberMessageType.Item.ListingDetails.EndTime;
                            }
                            memberMessage.Title = memberMessageType.Item.Title;

                            if (memberMessageType.Item.SellingStatus != null)
                            {
                                memberMessage.CurrentPrice = memberMessageType.Item.SellingStatus.CurrentPrice.Value;
                            }
                        }
                        memberMessage.SellerId = sellerId;
                        ebayMemberMessageList.Add(memberMessage);
                    }

                    pageCounter++;
                    retryCount = 0;

                    if (pageCounter > response.PaginationResult.TotalNumberOfPages)
                    {
                        //Reach last Page 
                        finished = true;
                    }
                }
                else
                {
                    //Response Contains 0 item
                    finished = true;
                }
            }
            while (!finished);

            return ebayMemberMessageList;
        }
        private int VerifyMessageStatus(int sellerId, Int64 msgId, string sendorId, int entriesPerPage)
        {
            List<EbayMessageType> msgList = GetMemberMessages(sellerId, sendorId, MessageStatusTypeCodeType.Answered,
                DateTime.Parse("2008-07-11 08:48:00"), entriesPerPage);
            if (msgList != null)
            {
                foreach (EbayMessageType msg in msgList)
                {
                    if (msg.MessageId == msgId)
                    {
                        return msg.MessageStatus;
                    }
                }
            }
            return -1;
        }
        public bool AddMemberMessageRTQ(int sellerId, string itemID, string subject, string body, string parentMessageId, string recipientID, int entriesPerPage)
        {
            bool result = false;
            string apiName = "AddMemberMessageRTQ";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            AddMemberMessageRTQRequestType request = new AddMemberMessageRTQRequestType();
            request.Version = _Credentials.Version.ToString();

            //required
            if (ConvertUtility.ToInt64(itemID) > 0)
            {
                request.ItemID = itemID;
            }
            request.MemberMessage = new MemberMessageType();
            request.MemberMessage.Subject = subject;
            request.MemberMessage.Body = body;
            request.MemberMessage.ParentMessageID = parentMessageId;
            request.MemberMessage.RecipientID = recipientID.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            //request.MemberMessage.DisplayToPublic = true;
            request.MemberMessage.DisplayToPublic = false;
            request.MemberMessage.DisplayToPublicSpecified = true;
            int retryCount = 0;
            while (retryCount <= _ApiMaxRetry && result == false)
            {
                try
                {
                    AddMemberMessageRTQResponseType response = service.AddMemberMessageRTQ(request);
                    if (response.Errors != null)
                    {
                        foreach (ErrorType err in response.Errors)
                        {
                            EbayErrorData.InsertErrorAddMemberMessageRTQ(sellerId, Convert.ToInt64(parentMessageId), EbayErrorTypeEnum.SysLevel, ConvertUtility.ToInt(err.ErrorCode), err.LongMessage, _EbayStatConn);
                        }
                    }
                    if (response.Ack == AckCodeType.Success)
                    {
                        result = true;
                    }
                }
                catch (Exception ex)
                {
                    EbayErrorData.InsertErrorAddMemberMessageRTQ(sellerId, Convert.ToInt64(parentMessageId), EbayErrorTypeEnum.ApiLevel, 0, ex.ToString(), _EbayStatConn);
                    //Sleep
                    System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                    //detect this message whether send success
                    if (VerifyMessageStatus(sellerId, Convert.ToInt64(parentMessageId), recipientID, entriesPerPage) == Convert.ToInt32(MessageStatusTypeCodeType.Answered))
                    {
                        return true;//Replied Success.
                    }
                }
                retryCount++;
            }
            return result;
        }

        public List<EbayBidderType> GetItemTransactions(long itemId, DateTime startDate, int entriesPerPage, Action<int, string> trace)
        {
            string apiName = "GetItemTransactions"; 
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            List<EbayBidderType> ebayBidderList = new List<EbayBidderType>();
            //GetOrdersResponseType testOrder = new GetOrdersResponseType();
            
            GetItemTransactionsRequestType request = new GetItemTransactionsRequestType();
            request.Version = _Credentials.Version.ToString();
            request.DetailLevel = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnAll };
            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.EntriesPerPage = entriesPerPage;
            request.Pagination.PageNumberSpecified = true;
            request.ModTimeFromSpecified = true;
            request.ModTimeToSpecified = true;
            request.ItemID = itemId.ToString();
            GetItemTransactionsResponseType response = null;


            
            List<string> transIdList = new List<string>();
            int bidIdx = 0;
            //Loop the ModTime
            const int modDayRange = 29;//max ModTime Day Ranage is 30 days

            DateTime modTimeFrom = DateTimeUtility.ToBeginingOfTheDay(startDate);
            bool modTimeFinished = false;
            do
            {
                request.ModTimeFrom = modTimeFrom.AddMinutes(-1);
                request.ModTimeTo = modTimeFrom.AddDays(modDayRange).AddMinutes(1);

                trace(0, String.Format("  Processing from  {0}  to  {1}..."
                    , request.ModTimeFrom.ToString("MM/dd/yy  HH:mm")
                    , request.ModTimeTo.ToString("MM/dd/yy  HH:mm")));

                //Loop the page
                int pageCounter = 1;
                bool finished = false;
                do
                {
                    request.Pagination.PageNumber = pageCounter;
                    int retryCount = 0;
                    while (retryCount <= _ApiMaxRetry)
                    {
                        try
                        {
                            //Must have a count update before anycall
                            UpdateSessionCallCount(apiName, ref service);
                            response = service.GetItemTransactions(request);
                            break;
                        }
                        catch (Exception ex)
                        {
                            //=========================
                            //RESPONSE ERROR (SYS LEVEL)
                            //=========================
                            EbayErrorData.InsertErrorGetItemTransactions(itemId,
                                request.ModTimeFrom, request.ModTimeTo, entriesPerPage,
                                pageCounter, EbayErrorTypeEnum.SysLevel, -1, ex.Message,
                                _EbayStatConn);

                            //Sleep
                            System.Threading.Thread.Sleep(_RetrySleepTime);
                            retryCount++;
                            //Break  
                            if (retryCount > _ApiMaxRetry)
                            {
                                break;
                            }
                        }
                    }
                    if (response == null)
                    {
                        //Return null if any page cannot response for each item.
                        return null;
                    }

                    if (response.PaginationResult != null)
                    {
                        trace(0, String.Format("    page {0} of {1}", pageCounter, response.PaginationResult.TotalNumberOfPages));
                    }

                    //=========================
                    //RESPONSE ERROR (APP LEVEL)
                    //=========================
                    if (response.Errors != null)
                    {
                        foreach (ErrorType errType in response.Errors)
                        {
                            EbayErrorData.InsertErrorGetItemTransactions(itemId,
                                 request.ModTimeFrom, request.ModTimeTo, entriesPerPage,
                                 pageCounter, EbayErrorTypeEnum.ApiLevel,
                                 ConvertUtility.ToInt(errType.ErrorCode),
                                 errType.LongMessage, _EbayStatConn);
                            if (errType.ErrorCode == "17")
                            {
                                EbayListingData.UpdateListingWithGTCStatus(itemId, EbayListingStatusEnum.EbayDeleted, _EbayStatConn);
                            }
                        }
                        //Return null if any page cannot response for each item.
                        return null;
                    }

                    if (response.TransactionArray != null && response.TransactionArray.Length > 0)
                    {
                        foreach (TransactionType tranType in response.TransactionArray)
                        {
                            if (transIdList.Contains(tranType.TransactionID))
                            {
                                continue;
                            }
                            else
                            {
                                transIdList.Add(tranType.TransactionID);
                            }
                            EbayBidderType bidderItem = new EbayBidderType();
                            bidderItem.ItemId = itemId;
                            bidderItem.BidIdx = bidIdx;
                            bidderItem.BidderId = tranType.Buyer.UserID;
                            bidderItem.BidQty = tranType.QuantityPurchased;
                            bidderItem.BidPrice = ConvertUtility.ToDecimal(tranType.TransactionPrice.Value);
                            bidderItem.BidCurrency = GetCurrencyId(ConvertUtility.Trim(tranType.TransactionPrice.currencyID));
                            bidderItem.ConvertedBidPrice = ConvertUtility.ToDecimal(tranType.ConvertedTransactionPrice.Value);
                            bidderItem.Bidtime = tranType.CreatedDate;
                            bidderItem.BidAction = 0; //Unknown: Can not get BidAction by this call

                            if (!string.IsNullOrEmpty(tranType.Buyer.Email))
                            {
                                string email = tranType.Buyer.Email;
                            }
                            ebayBidderList.Add(bidderItem);
                            bidIdx++;
                        }

                        pageCounter++;
                        if (pageCounter > response.PaginationResult.TotalNumberOfPages)
                        {
                            //Reach last Page 
                            finished = true;
                        }
                    }
                    else
                    {
                        //No Bidder for this range of modTime
                        //pageCounter should be 1
                        if (pageCounter != 1)
                        {
                            EbayErrorData.InsertErrorGetItemTransactions(itemId,
                                 request.ModTimeFrom, request.ModTimeTo, entriesPerPage,
                                 pageCounter, EbayErrorTypeEnum.ApiLevel, -1,
                                 "Nothing in response.TransactionArray.", _EbayStatConn);
                            return null;
                        }
                        else
                        {
                            EbayErrorData.InsertErrorGetItemTransactions(itemId,
                                 request.ModTimeFrom, request.ModTimeTo, entriesPerPage,
                                 pageCounter, EbayErrorTypeEnum.ApiLevel, -1,
                                 "Null TransactionArray.", _EbayStatConn);
                            EbayListingData.UpdateListingWithGTCStatus(itemId, EbayListingStatusEnum.EbayDeleted, _EbayStatConn);
                            return null;
                        }
                        //finished = true;
                    }
                }//end do (page loop)
                while (!finished);
                if (request.ModTimeTo >= DateTime.Now.ToUniversalTime())
                {
                    modTimeFinished = true;
                }
                modTimeFrom = modTimeFrom.AddDays(modDayRange);
            }//end do (modTime loop)
            while (!modTimeFinished);
            if (ebayBidderList.Count <= 0)
            {
                //When use this call for getting bidders, it means that the listing has large sales
                //ie. it should not be zero bidders.
                EbayErrorData.InsertErrorGetItemTransactions(itemId, request.ModTimeFrom, request.ModTimeTo,
                    entriesPerPage, -1, EbayErrorTypeEnum.SysLevel, -1, "No bidders.", _EbayStatConn);
                return null;
            }
            return ebayBidderList;
        }

        public EbayListingItemType GetItemLost(long itemId)
        {
            string apiName = "GetItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetItemRequestType getitemRequest = new GetItemRequestType();

            getitemRequest.DetailLevel = new DetailLevelCodeType[1] { DetailLevelCodeType.ItemReturnDescription };
            getitemRequest.ItemID = ConvertUtility.Trim(itemId);

            getitemRequest.Version = _Credentials.Version.ToString();

            EbayListingItemType listingItem = new EbayListingItemType();
            listingItem.ItemId = itemId;

            GetItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetItem(getitemRequest);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                return null;
            }

            if (response.Errors != null)
            {
                foreach (ErrorType errType in response.Errors)
                {
                    if (errType.ErrorCode == "17")
                    {
                        //Item is invalid, not activated, or no longer in our database, or an Live Auction item.
                        listingItem.ListingStatus = EbayListingStatusEnum.EbayDeleted;
                        return listingItem;
                    }
                    else
                    {
                        EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.ApiLevel, errType.LongMessage, _EbayStatConn);
                    }
                }
                return null;
            }

            //================
            //PROCESS RESPONSE
            //================
            if (response.Item == null)
            {
                //response.Item should be Always return
                EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.SysLevel, "response.Item is null.", _EbayStatConn);
                return null;
            }
            if (response.Item.ListingDetails == null)
            {
                //response.Item.ListingDetails should be Always return
                EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.SysLevel, "response.Item.ListingDetails is null.", _EbayStatConn);
                return null;
            }
            if (response.Item.Seller != null)
            {
                if (response.Item.Seller.SellerInfo != null)
                {
                    if (response.Item.Seller.SellerInfo.TopRatedSellerSpecified)
                    {
                        listingItem.TopRatedSeller = response.Item.Seller.SellerInfo.TopRatedSeller;
                    }
                }
            }
            if (response.Item.PictureDetails != null)
            {
                if (response.Item.PictureDetails.GalleryTypeSpecified)
                {
                    listingItem.GalleryType = GetGalleryTypeId(response.Item.PictureDetails.GalleryType.ToString());
                }
            }
            if (response.Item.SellingStatus != null)
            {
                listingItem.QtySold = response.Item.SellingStatus.QuantitySold;

                if (response.Item.SellingStatus.ListingStatusSpecified)
                {
                    if (response.Item.SellingStatus.ListingStatus == ListingStatusCodeType.Ended
                        || response.Item.SellingStatus.ListingStatus == ListingStatusCodeType.Completed)
                    {
                        //Listing has ended
                        if (listingItem.QtySold == 0)
                        {
                            listingItem.ListingStatus = EbayListingStatusEnum.Completed;
                        }
                        else
                        {
                            listingItem.ListingStatus = EbayListingStatusEnum.Ended;
                        }
                        listingItem.FinalEndDateTime = response.Item.ListingDetails.EndTime;
                    }
                    else
                    {
                        if (GetListingDurationId(response.Item.ListingDuration) == 255)
                        {
                            if (listingItem.QtySold == 0)
                            {
                                listingItem.ListingStatus = EbayListingStatusEnum.GTCBidderLoaded;
                            }
                            else
                            {
                                listingItem.ListingStatus = EbayListingStatusEnum.GTCRelisted;
                            }
                            listingItem.EndDateTime = response.Item.ListingDetails.EndTime;
                        }
                        else
                        {
                            //Non GTC Relist - Duration change, listingtype may change
                            listingItem.ListingStatus = EbayListingStatusEnum.New;
                            listingItem.EndDateTime = response.Item.ListingDetails.EndTime;
                            listingItem.ListingDurationId = GetListingDurationId(response.Item.ListingDuration);
                            listingItem.ListingType = GetListingTypeId(response.Item.ListingType.ToString());
                        }
                    }
                }
            }
            else
            {
                //response.Item.SellingStatus should be Always return
                listingItem.QtySold = 0;
                //If EndDate < eBay processed the request Time -> Endend
                if (response.Item.ListingDetails.EndTime < response.Timestamp)
                {
                    //Listing has ended
                    listingItem.ListingStatus = EbayListingStatusEnum.Completed;
                    listingItem.FinalEndDateTime = response.Item.ListingDetails.EndTime;
                }
            }

            ItemType itemType = response.Item;
            listingItem.BuyItNowPrice = ConvertUtility.ToDecimal(itemType.BuyItNowPrice.Value);
            listingItem.ConvertedBuyItNowPrice = ConvertUtility.ToDecimal(itemType.ListingDetails.ConvertedBuyItNowPrice.Value);
            #region ShippingDetails
            if (itemType.ShippingDetails.ShippingServiceOptions != null)
            {
                foreach (ShippingServiceOptionsType shippingServiceOptions in itemType.ShippingDetails.ShippingServiceOptions)
                {
                    EbayShippingServiceType eBayShipping = new EbayShippingServiceType();
                    if (shippingServiceOptions.ShippingService != null)
                    {
                        eBayShipping.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);
                    }
                    else
                    {
                        eBayShipping.ShippingServiceId = GetShippingServiceId("NA", shippingServiceOptions.ExpeditedService);
                    }
                    if (shippingServiceOptions.ShippingServiceCost != null)
                    {
                        eBayShipping.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                        eBayShipping.ShippingServiceCurrency = GetCurrencyId(shippingServiceOptions.ShippingServiceCost.currencyID.ToString());

                        #region GetStandardShipping
                        if (shippingServiceOptions.ShippingService.ToLower().Contains("standard")
                            && eBayShipping.ShippingServiceCurrency == listingItem.Currency)
                        {
                            //Standard Only
                            if (listingItem.ShippingServiceCost == -1 ||
                                (listingItem.ShippingServiceCost != -1 &&
                                ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value)
                                < listingItem.ShippingServiceCost))
                            {
                                listingItem.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                                //ByEric
                                listingItem.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);

                                if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                                {
                                    listingItem.ShippingAdditionCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                                }
                                else
                                {
                                    listingItem.ShippingAdditionCost = 0;
                                }

                                if (shippingServiceOptions.ShippingSurcharge != null)
                                {
                                    listingItem.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                                }
                                else
                                {
                                    listingItem.ShippingSurcharge = 0;
                                }
                            }
                        }
                        #endregion
                    }
                    if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                    {
                        eBayShipping.ShippingServiceAdditionalCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                    }
                    if (shippingServiceOptions.ShippingSurcharge != null)
                    {
                        eBayShipping.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                    }

                    //Add by Joseph 20100519
                    eBayShipping.ExpeditedService = shippingServiceOptions.ExpeditedService;

                    listingItem.ShippingServiceList.Add(eBayShipping);
                }
                #region If no StandardShipping, use the minimum
                if (listingItem.ShippingServiceCost == -1)
                {
                    //NO Standard In the List, Pick the cheapest one if any
                    foreach (ShippingServiceOptionsType shippingServiceOptions in itemType.ShippingDetails.ShippingServiceOptions)
                    {
                        if (shippingServiceOptions.ShippingServiceCost != null)
                        {
                            if (listingItem.ShippingServiceCost == -1 || (
                                ConvertUtility.ToDecimal
                                (shippingServiceOptions.ShippingServiceCost.Value)
                                < listingItem.ShippingServiceCost))
                            {
                                listingItem.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                                //ByEric
                                listingItem.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);

                                if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                                {
                                    listingItem.ShippingAdditionCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                                }
                                else
                                {
                                    listingItem.ShippingAdditionCost = 0;
                                }
                                if (shippingServiceOptions.ShippingSurcharge != null)
                                {
                                    listingItem.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                                }
                                else
                                {
                                    listingItem.ShippingSurcharge = 0;
                                }
                            }
                        }
                    }
                }
                #endregion
            }
            #region If no valid shipping free, set them to zero
            if (listingItem.ShippingServiceCost == -1)
            {
                //ByEric
                listingItem.ShippingServiceId = 13;
                listingItem.ShippingServiceCost = 0;
                listingItem.ShippingAdditionCost = 0;
                listingItem.ShippingSurcharge = 0;
            }
            #endregion
            #endregion
            #region ListingEnhancement
            if (itemType.ListingEnhancement != null)
            {
                foreach (ListingEnhancementsCodeType listingEnhancement in itemType.ListingEnhancement)
                {
                    listingItem.ListingEnhancementType.Add(GetListingEnhancementCodeTypeId(listingEnhancement.ToString()));
                }
            }
            #endregion

            listingItem.FeaturedType = EbayListingData.GetFeaturedType(listingItem.AuctionSite, listingItem.TopRatedSeller, listingItem.GalleryType, listingItem.ListingEnhancementType);

            return listingItem;
        }

        public EbayListingItemType GetItemListing(long itemId, int sellerId, bool isOwner, EbayListingStatusEnum listingStatus, DateTime utcEndDate)
        {
            string apiName = "GetItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetItemRequestType getitemRequest = new GetItemRequestType();

            getitemRequest.DetailLevel = new DetailLevelCodeType[1] { DetailLevelCodeType.ItemReturnDescription };
            getitemRequest.ItemID = ConvertUtility.Trim(itemId);

            getitemRequest.Version = _Credentials.Version.ToString();

            EbayListingItemType listingItem = new EbayListingItemType();
            listingItem.ItemId = itemId;

            GetItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetItem(getitemRequest);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.SysLevel, ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                return null;
            }

            if (response.Errors != null)
            {
                foreach (ErrorType errType in response.Errors)
                {
                    if (errType.ErrorCode == "17")
                    {
                        //Item is invalid, not activated, or no longer in our database, or an Live Auction item.
                        listingItem.ListingStatus = EbayListingStatusEnum.EbayDeleted;
                        return listingItem;
                    }
                    else
                    {
                        EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.ApiLevel, errType.LongMessage, _EbayStatConn);
                    }
                }
                return null;
            }

            //================
            //PROCESS RESPONSE
            //================
            if (response.Item == null)
            {
                //response.Item should be Always return
                EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.SysLevel, "response.Item is null.", _EbayStatConn);
                return null;
            }
            if (response.Item.ListingDetails == null)
            {
                //response.Item.ListingDetails should be Always return
                EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.SysLevel, "response.Item.ListingDetails is null.", _EbayStatConn);
                return null;
            }

            ItemType itemType = response.Item;

            listingItem.ItemId = ConvertUtility.ToInt64(itemType.ItemID);
            listingItem.SKU = ConvertUtility.Trim(itemType.SKU);
            listingItem.SellerID = sellerId;

            listingItem.StartDateTime = itemType.ListingDetails.StartTime;
            listingItem.EndDateTime = itemType.ListingDetails.EndTime;

            listingItem.ListingDurationId = GetListingDurationId(itemType.ListingDuration);
            listingItem.Title = ConvertUtility.Trim(itemType.Title);
            listingItem.SubTitle = ConvertUtility.Trim(itemType.SubTitle);
            listingItem.AuctionSite = GetSiteId(itemType.Site.ToString());

            listingItem.Currency = GetCurrencyId(itemType.Currency.ToString());
            listingItem.StartPrice = ConvertUtility.ToDecimal(itemType.StartPrice.Value);
            listingItem.ConvertedStartPrice = ConvertUtility.ToDecimal(itemType.ListingDetails.ConvertedStartPrice.Value);
            listingItem.BuyItNowPrice = ConvertUtility.ToDecimal(itemType.BuyItNowPrice.Value);
            listingItem.ConvertedBuyItNowPrice = ConvertUtility.ToDecimal(itemType.ListingDetails.ConvertedBuyItNowPrice.Value);

            listingItem.QtyLaunch = itemType.Quantity;
            listingItem.ListingStatus = listingStatus;

            if (isOwner)
            {
                string plPattern = @"\?[\s\S]*pl=(\d+)";
                if (itemType.PictureDetails != null)
                {
                    string imageUrl = itemType.PictureDetails.GalleryURL;
                    if (!string.IsNullOrEmpty(imageUrl))
                    {
                        if (Regex.IsMatch(imageUrl, plPattern))
                        {
                            listingItem.ProductLine = ConvertUtility.ToInt(Regex.Match(imageUrl, plPattern).Groups[1].Value);
                        }
                    }
                }
            }
            listingItem.ProductLine = listingItem.ProductLine <= 0 ? 99 : listingItem.ProductLine;

            if (itemType.SellingStatus != null)
            {
                listingItem.QtySold = itemType.SellingStatus.QuantitySold;
                if (itemType.SellingStatus.ListingStatusSpecified)
                {
                    if (itemType.SellingStatus.ListingStatus == ListingStatusCodeType.Ended
                        || itemType.SellingStatus.ListingStatus == ListingStatusCodeType.Completed)
                    {
                        //Listing has ended
                        if (listingItem.QtySold == 0)
                        {
                            listingItem.ListingStatus = EbayListingStatusEnum.Completed;
                        }
                        else
                        {
                            listingItem.ListingStatus = EbayListingStatusEnum.Ended;
                        }
                        listingItem.FinalEndDateTime = itemType.ListingDetails.EndTime;
                    }
                }
                else
                {
                    //If rawlisting's EndDate is past, and GTC
                    if (listingItem.EndDateTime > utcEndDate
                        && GetListingDurationId(response.Item.ListingDuration) == 255)
                    {
                        if (listingItem.QtySold == 0)
                        {
                            listingItem.ListingStatus = EbayListingStatusEnum.GTCBidderLoaded;
                        }
                        else
                        {
                            listingItem.ListingStatus = EbayListingStatusEnum.GTCRelisted;
                        }
                    }
                }
            }

            listingItem.ListingType = GetListingTypeId(itemType.ListingType.ToString());

            //Add by Candy 20091021
            if (itemType.Seller != null)
            {
                if (itemType.Seller.SellerInfo != null)
                {
                    if (itemType.Seller.SellerInfo.TopRatedSellerSpecified)
                    {
                        listingItem.TopRatedSeller = itemType.Seller.SellerInfo.TopRatedSeller;
                    }
                }
            }

            if (itemType.PictureDetails != null)
            {
                if (itemType.PictureDetails.GalleryTypeSpecified)
                {
                    listingItem.GalleryType = GetGalleryTypeId(itemType.PictureDetails.GalleryType.ToString());
                }
            }
            listingItem.CategoryId = ConvertUtility.ToInt(itemType.PrimaryCategory.CategoryID);


            #region ShippingDetails
            if (itemType.ShippingDetails.ShippingServiceOptions != null)
            {
                foreach (ShippingServiceOptionsType shippingServiceOptions in itemType.ShippingDetails.ShippingServiceOptions)
                {
                    EbayShippingServiceType eBayShipping = new EbayShippingServiceType();
                    if (shippingServiceOptions.ShippingService != null)
                    {
                        eBayShipping.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);
                    }
                    else
                    {
                        eBayShipping.ShippingServiceId = GetShippingServiceId("NA", shippingServiceOptions.ExpeditedService);
                    }
                    if (shippingServiceOptions.ShippingServiceCost != null)
                    {
                        eBayShipping.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                        eBayShipping.ShippingServiceCurrency = GetCurrencyId(shippingServiceOptions.ShippingServiceCost.currencyID.ToString());

                        #region GetStandardShipping
                        if (shippingServiceOptions.ShippingService.ToLower().Contains("standard")
                            && eBayShipping.ShippingServiceCurrency == listingItem.Currency)
                        {
                            //Standard Only
                            if (listingItem.ShippingServiceCost == -1 ||
                                (listingItem.ShippingServiceCost != -1 &&
                                ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value)
                                < listingItem.ShippingServiceCost))
                            {
                                listingItem.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                                //ByEric
                                listingItem.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);

                                if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                                {
                                    listingItem.ShippingAdditionCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                                }
                                else
                                {
                                    listingItem.ShippingAdditionCost = 0;
                                }

                                if (shippingServiceOptions.ShippingSurcharge != null)
                                {
                                    listingItem.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                                }
                                else
                                {
                                    listingItem.ShippingSurcharge = 0;
                                }
                            }
                        }
                        #endregion
                    }
                    if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                    {
                        eBayShipping.ShippingServiceAdditionalCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                    }
                    if (shippingServiceOptions.ShippingSurcharge != null)
                    {
                        eBayShipping.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                    }

                    listingItem.ShippingServiceList.Add(eBayShipping);
                }
                #region If no StandardShipping, use the minimum
                if (listingItem.ShippingServiceCost == -1)
                {
                    //NO Standard In the List, Pick the cheapest one if any
                    foreach (ShippingServiceOptionsType shippingServiceOptions in itemType.ShippingDetails.ShippingServiceOptions)
                    {
                        if (shippingServiceOptions.ShippingServiceCost != null)
                        {
                            if (listingItem.ShippingServiceCost == -1 || (
                                ConvertUtility.ToDecimal
                                (shippingServiceOptions.ShippingServiceCost.Value)
                                < listingItem.ShippingServiceCost))
                            {
                                listingItem.ShippingServiceCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceCost.Value);
                                //ByEric
                                listingItem.ShippingServiceId = GetShippingServiceId(shippingServiceOptions.ShippingService, shippingServiceOptions.ExpeditedService);

                                if (shippingServiceOptions.ShippingServiceAdditionalCost != null)
                                {
                                    listingItem.ShippingAdditionCost = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingServiceAdditionalCost.Value);
                                }
                                else
                                {
                                    listingItem.ShippingAdditionCost = 0;
                                }
                                if (shippingServiceOptions.ShippingSurcharge != null)
                                {
                                    listingItem.ShippingSurcharge = ConvertUtility.ToDecimal(shippingServiceOptions.ShippingSurcharge.Value);
                                }
                                else
                                {
                                    listingItem.ShippingSurcharge = 0;
                                }
                            }
                        }
                    }
                }
                #endregion
            }
            #region If no valid shipping free, set them to zero
            if (listingItem.ShippingServiceCost == -1)
            {
                //ByEric
                listingItem.ShippingServiceId = 13;
                listingItem.ShippingServiceCost = 0;
                listingItem.ShippingAdditionCost = 0;
                listingItem.ShippingSurcharge = 0;
            }
            #endregion
            #endregion

            #region ListingEnhancement
            if (itemType.ListingEnhancement != null)
            {
                foreach (ListingEnhancementsCodeType listingEnhancement in itemType.ListingEnhancement)
                {
                    listingItem.ListingEnhancementType.Add(GetListingEnhancementCodeTypeId(listingEnhancement.ToString()));
                }
            }
            #endregion

            return listingItem;
        }

        public string GetItemXml(long itemId)
        {
            string apiName = "GetItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetItemRequestType getitemRequest = new GetItemRequestType();

            DetailLevelCodeType[] dvt = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnAll };
            getitemRequest.DetailLevel = dvt;
            getitemRequest.ItemID = ConvertUtility.Trim(itemId);
            getitemRequest.IncludeItemSpecificsSpecified = true;
            getitemRequest.IncludeItemSpecifics = true;

            getitemRequest.Version = _Credentials.Version.ToString();

            GetItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetItem(getitemRequest);
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }

            return XmlUtility.SerializeToString(response, false);
        }

        public bool SetPromotionalSale(EbayPromoMarkdownSaleType promoSale, out long promotionalSaleID, out string errLog, bool logReqtAndResp)
        {
            string apiName = "SetPromotionalSale";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            SetPromotionalSaleRequestType request = new SetPromotionalSaleRequestType();
            request.Version = _Credentials.Version.ToString();
            PromotionalSaleType promo = new PromotionalSaleType();

            request.ActionSpecified = true;
            request.Action = ModifyActionCodeType.Add;
            /*if (request.Action != ModifyActionCodeType.Add)
            {
                promo.PromotionalSaleIDSpecified = true;
                promo.PromotionalSaleID = 0;
            }*/

            promo.DiscountTypeSpecified = true;
            promo.DiscountValueSpecified = true;
            promo.PromotionalSaleType1Specified = true;
            promo.PromotionalSaleStartTimeSpecified = true;
            promo.PromotionalSaleEndTimeSpecified = true;

            promo.PromotionalSaleName = promoSale.PromoSaleName;
            promo.DiscountType = promoSale.DiscountType == EbayPromoDiscountTypeEnum.Percentage ? DiscountCodeType.Percentage : DiscountCodeType.Price;
            promo.DiscountValue = promoSale.DiscountValue; //Discount Off
            promo.PromotionalSaleStartTime = promoSale.PromoStartDate;
            promo.PromotionalSaleEndTime = promoSale.PromoEndDate;
            if (promoSale.PromoSaleType == EbayPromoSaleTypeEnum.PriceDiscountAndFreeShipping)
            {
                promo.PromotionalSaleType1 = PromotionalSaleTypeCodeType.PriceDiscountAndFreeShipping;
            }
            else
            {
                promo.PromotionalSaleType1 = PromotionalSaleTypeCodeType.PriceDiscountOnly;
            }

            request.PromotionalSaleDetails = promo;

            #region promoSaleMsg - For Log Error Msg
            const int errMsgMaxLen = 3500; //error msg exclude promoSaleMsg

            StringBuilder promoSaleMsg = new StringBuilder();
            promoSaleMsg.AppendLine("PromoSaleName: " + promoSale.PromoSaleName);
            promoSaleMsg.AppendLine("PromoStartDate: " + promoSale.PromoStartDate.ToString("yyyy-M-d HH:mm"));
            promoSaleMsg.AppendLine("PromoEndDate: " + promoSale.PromoEndDate.ToString("yyyy-M-d HH:mm"));
            promoSaleMsg.AppendLine("DiscountValue: " + promoSale.DiscountValue);
            promoSaleMsg.AppendLine("DiscountType: " + promoSale.DiscountType);
            promoSaleMsg.AppendLine("PromoSaleType: " + promoSale.PromoSaleType);
            #endregion

            errLog = string.Empty;
            promotionalSaleID = 0;
            SetPromotionalSaleResponseType response = null;
            try
            {
                UpdateSessionCallCount(apiName, ref service);
                response = service.SetPromotionalSale(request);
                #region Log Request and Response
                if (logReqtAndResp)
                {
                    string requestXml = string.Empty;
                    string responseXml = string.Empty;
                    try
                    {
                        requestXml = XmlUtility.SerializeToString(request, false);
                        responseXml = XmlUtility.SerializeToString(response, false);
                        EbayPromoMarkdownData.InsertPromoMarkdownApiLog(apiName, response.PromotionalSaleID, -1, requestXml, responseXml, _EbayStatConn);
                    }
                    catch (Exception ex)
                    {
                        errLog += "\r\nLogReqtAndRespError:" + ex.Message + "\r\n" + requestXml + responseXml;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                //Log Error
                string errMsg = "Error: " + ex.Message + "\r\n" + promoSaleMsg.ToString();
                EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, string.Empty, errMsg, _EbayStatConn);
                errLog = "Error: " + ex.Message;
                return false;
            }
            promotionalSaleID = response.PromotionalSaleID;
            bool promotionalSaleIDSpecified = response.PromotionalSaleIDSpecified;
            bool promotionalSaleStatusSpecified = response.PromotionalSaleIDSpecified;
            PromotionalSaleStatusCodeType promotionalSaleStatus = response.Status;
            /* PromotionalSaleStatusCodeType:
             * Scheduled - Not yet started promotional, scheduled to be started
             * Deleted - Manually deleted the promotional sale before promotion started
             * Processing
             * Active - during promotion period
             * Inactive - after promotion period
            */
            if (response.Ack == AckCodeType.Success)
            {
                switch (request.Action)
                {
                    case ModifyActionCodeType.Add:
                        return promotionalSaleIDSpecified && promotionalSaleID > 0;
                    case ModifyActionCodeType.Delete:
                        return promotionalSaleStatusSpecified && promotionalSaleStatus == PromotionalSaleStatusCodeType.Deleted;
                    case ModifyActionCodeType.Update:
                        return promotionalSaleStatusSpecified && promotionalSaleStatus == PromotionalSaleStatusCodeType.Scheduled;
                }
            }
            else
            {
                if (response.Errors != null)
                {
                    foreach (ErrorType error in response.Errors)
                    {
                        //Log Error
                        EbayErrorStatusEnum errStatus = EbayErrorStatusEnum.Failure;
                        if (response.Ack == AckCodeType.Warning)
                        {
                            errStatus = EbayErrorStatusEnum.Warning;
                        }
                        string errCode = error.ErrorCode;
                        string errMsg = "Error: " + error.LongMessage + "\r\n" + promoSaleMsg.ToString();
                        errLog += "Error: " + error.LongMessage + " ";
                        EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.ApiLevel, errStatus, errCode, errMsg, _EbayStatConn);
                    }
                }
                if (response.Ack == AckCodeType.Warning)
                {
                    switch (request.Action)
                    {
                        case ModifyActionCodeType.Add:
                            return promotionalSaleID > 0;
                        case ModifyActionCodeType.Delete:
                            return promotionalSaleStatus == PromotionalSaleStatusCodeType.Deleted;
                        case ModifyActionCodeType.Update:
                            return promotionalSaleStatus == PromotionalSaleStatusCodeType.Scheduled;
                    }
                }
            }
            return false;
        }

        /// <param name="IsDeleting">True: Action is 'Delete'; False: Action is 'Add'</param>
        public bool SetPromotionalSaleListings(long promotionalSaleID, List<long> itemIdList, bool isDeleting, out string errLog, bool logReqtAndResp)
        {
            string apiName = "SetPromotionalSaleListings";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            SetPromotionalSaleListingsRequestType request = new SetPromotionalSaleListingsRequestType();
            request.Version = _Credentials.Version.ToString();

            request.ActionSpecified = true;
            request.PromotionalSaleIDSpecified = true;
            request.AllAuctionItemsSpecified = true;
            request.AllFixedPriceItemsSpecified = true;
            request.AllStoreInventoryItemsSpecified = true;

            request.AllAuctionItems = false;
            request.AllFixedPriceItems = false;
            request.AllStoreInventoryItems = false;

            request.Action = isDeleting ? ModifyActionCodeType.Delete : ModifyActionCodeType.Add;
            request.PromotionalSaleID = promotionalSaleID;
            request.PromotionalSaleItemIDArray = new ItemIDArrayType();
            string[] itemIds = new string[itemIdList.Count];
            for (int idx = 0; idx < itemIdList.Count; idx++)
            {
                itemIds[idx] = itemIdList[idx].ToString();
            }
            request.PromotionalSaleItemIDArray.ItemID = itemIds;

            errLog = string.Empty;
            SetPromotionalSaleListingsResponseType response = null;
            try
            {
                UpdateSessionCallCount(apiName, ref service);
                response = service.SetPromotionalSaleListings(request);
                #region Log Request and Response
                if (logReqtAndResp)
                {
                    string requestXml = string.Empty;
                    string responseXml = string.Empty;
                    try
                    {
                        requestXml = XmlUtility.SerializeToString(request, false);
                        responseXml = XmlUtility.SerializeToString(response, false);
                        if (isDeleting)
                        {
                            EbayPromoMarkdownData.InsertPromoMarkdownApiLog(apiName + "(DEL)", promotionalSaleID, itemIdList[0], requestXml, responseXml, _EbayStatConn);
                        }
                        else
                        {
                            EbayPromoMarkdownData.InsertPromoMarkdownApiLog(apiName, promotionalSaleID, itemIdList[0], requestXml, responseXml, _EbayStatConn);
                        }
                    }
                    catch (Exception ex)
                    {
                        errLog += "\r\nLogReqtAndRespError:" + ex.Message + "\r\n" + requestXml + responseXml;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                errLog = "Error: " + ex.Message;
                //Log Error
                foreach (long itemId in itemIdList)
                {
                    EbayErrorData.InsertErrorSetPromotionalSaleListings(itemId, promotionalSaleID, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, string.Empty, ex.Message, _EbayStatConn);
                }
                return false;
            }
            PromotionalSaleStatusCodeType promotionalSaleStatus = response.Status;
            if (response.Ack == AckCodeType.Success)
            {
                return true;
            }
            else
            {
                if (response.Errors != null)
                {
                    foreach (ErrorType error in response.Errors)
                    {
                        //Log Error
                        foreach (long itemId in itemIdList)
                        {
                            EbayErrorStatusEnum errStatus = EbayErrorStatusEnum.Failure;
                            if (response.Ack == AckCodeType.Warning)
                            {
                                errStatus = EbayErrorStatusEnum.Warning;
                            }
                            string errCode = error.ErrorCode;
                            string errMsg = error.LongMessage;
                            errLog += "Error: " + error.LongMessage + " ";
                            EbayErrorData.InsertErrorSetPromotionalSaleListings(itemId, promotionalSaleID, EbayErrorTypeEnum.ApiLevel, errStatus, errCode, errMsg, _EbayStatConn);
                        }
                    }
                }
                if (response.Ack == AckCodeType.Warning)
                {
                    errLog += "(Warning) ";
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public List<EbayPromoMarkdownSaleType> GetPromotionalSaleDetails(bool promotionalSaleIDSpecified, long promotionalSaleID, bool logReqtAndResp)
        {
            string apiName = "GetPromotionalSaleDetails";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            GetPromotionalSaleDetailsRequestType request = new GetPromotionalSaleDetailsRequestType();
            request.Version = _Credentials.Version.ToString();

            if (promotionalSaleIDSpecified)
            {
                request.PromotionalSaleIDSpecified = true;
                request.PromotionalSaleID = promotionalSaleID;
            }

            GetPromotionalSaleDetailsResponseType response = null;
            int retryCount = 0;
            do
            {
                try
                {
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetPromotionalSaleDetails(request);
                    #region Log Request and Response
                    if (logReqtAndResp)
                    {
                        string requestXml = string.Empty;
                        string responseXml = string.Empty;
                        try
                        {
                            requestXml = XmlUtility.SerializeToString(request, false);
                            responseXml = XmlUtility.SerializeToString(response, false);
                            EbayPromoMarkdownData.InsertPromoMarkdownApiLog(apiName, promotionalSaleID, -1, requestXml, responseXml, _EbayStatConn);
                        }
                        catch (Exception ex)
                        {
                            //Log Error
                            string errMsg = "LogReqtAndRespError: " + ex.Message;
                            if (promotionalSaleIDSpecified)
                            {
                                errMsg += "\r\nPromoSaleId: " + promotionalSaleID;
                            }
                            errMsg = TextUtility.SubStringIf(errMsg, 4000);
                            EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, string.Empty, errMsg, _EbayStatConn);
                        }
                    }
                    #endregion
                    break;
                }
                catch (Exception ex)
                {
                    //Log Error
                    string errMsg = "Error: " + ex.Message;
                    if (promotionalSaleIDSpecified)
                    {
                        errMsg += "\r\nPromoSaleId: " + promotionalSaleID;
                    }
                    errMsg = TextUtility.SubStringIf(errMsg, 4000);
                    EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, string.Empty, errMsg, _EbayStatConn);
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            while (true);
            if (response.Errors != null)
            {
                foreach (ErrorType error in response.Errors)
                {
                    //Error: Promotional sale not found for user.
                    if (error.ErrorCode == "219351")
                    {
                        //By Pass
                        continue;
                    }
                    //Log Error
                    EbayErrorStatusEnum errStatus = EbayErrorStatusEnum.Failure;
                    if (response.Ack == AckCodeType.Warning)
                    {
                        errStatus = EbayErrorStatusEnum.Warning;
                    }
                    string errCode = error.ErrorCode;
                    string errMsg = "Error: " + error.LongMessage;
                    if (promotionalSaleIDSpecified)
                    {
                        errMsg += "\r\nPromoSaleId: " + promotionalSaleID;
                    }
                    EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.ApiLevel, errStatus, errCode, errMsg, _EbayStatConn);
                }
            }
            if (response.Ack != AckCodeType.Success && response.Ack != AckCodeType.Warning)
            {
                return null;
            }
            List<EbayPromoMarkdownSaleType> promoSaleList = new List<EbayPromoMarkdownSaleType>();
            foreach (PromotionalSaleType promotionalSaleType in response.PromotionalSaleDetails)
            {
                EbayPromoMarkdownSaleType promoSale = new EbayPromoMarkdownSaleType();
                promoSale.PromoSaleId = promotionalSaleType.PromotionalSaleID;
                promoSale.PromoSaleName = promotionalSaleType.PromotionalSaleName;
                promoSale.PromoStartDate = promotionalSaleType.PromotionalSaleStartTime;
                promoSale.PromoEndDate = promotionalSaleType.PromotionalSaleEndTime;
                promoSale.DiscountValue = promotionalSaleType.DiscountValue;
                if (promotionalSaleType.DiscountType == DiscountCodeType.Percentage)
                {
                    promoSale.DiscountType = EbayPromoDiscountTypeEnum.Percentage;
                }
                else
                {
                    promoSale.DiscountType = EbayPromoDiscountTypeEnum.FixedAmount;
                }
                switch (promotionalSaleType.PromotionalSaleType1)
                {
                    case PromotionalSaleTypeCodeType.PriceDiscountOnly:
                        promoSale.PromoSaleType = EbayPromoSaleTypeEnum.PriceDiscountOnly;
                        break;
                    case PromotionalSaleTypeCodeType.PriceDiscountAndFreeShipping:
                        promoSale.PromoSaleType = EbayPromoSaleTypeEnum.PriceDiscountAndFreeShipping;
                        break;
                    case PromotionalSaleTypeCodeType.FreeShippingOnly:
                        promoSale.PromoSaleType = EbayPromoSaleTypeEnum.FreeShippingOnly;
                        break;
                    default:
                        if (promotionalSaleType.PromotionalSaleType1Specified)
                        {
                            throw new Exception("Unknown / New PromotionalSaleTypeCodeType:" + promotionalSaleType.PromotionalSaleType1);
                        }
                        else
                        {
                            throw new Exception("PromotionalSaleType1 is not specified.");
                        }
                }
                promoSale.Status = promotionalSaleType.Status.ToString();

                if (promotionalSaleType.PromotionalSaleItemIDArray != null
                    && promotionalSaleType.PromotionalSaleItemIDArray.ItemID != null)
                {
                    promoSale.ItemIdList = new List<long>();
                    foreach (string itemId in promotionalSaleType.PromotionalSaleItemIDArray.ItemID)
                    {
                        promoSale.ItemIdList.Add(ConvertUtility.ToInt64(itemId));
                    }
                }
                else
                {
                    promoSale.ItemIdList = null;
                }

                promoSaleList.Add(promoSale);
            }//end foreach PromotionalSaleDetails

            return promoSaleList;
        }

        public bool GetItemPromotionalSale(long itemId, long promoSaleId, DateTime promoStartDate, int minuteBuffer, bool logReqtAndResp)
        {
            string apiName = "GetItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetItemRequestType request = new GetItemRequestType();

            DetailLevelCodeType[] dvt = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnSummary };
            request.DetailLevel = dvt;
            request.ItemID = ConvertUtility.Trim(itemId);
            request.IncludeItemSpecificsSpecified = true;
            request.IncludeItemSpecifics = true;

            request.Version = _Credentials.Version.ToString();

            GetItemResponseType response;
            int retryCount = 0;
            do
            {
                try
                {
                    //Must have a count update before anycall
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetItem(request);
                    break;
                }
                catch (Exception ex)
                {
                    if (retryCount < _ApiMaxRetry)
                    {
                        retryCount++;
                        continue;
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            while (true);
            if (response != null && response.Item != null && response.Item.SellingStatus != null)
            {
                #region Log Request and Response
                if (logReqtAndResp)
                {
                    string requestXml = string.Empty;
                    string responseXml = string.Empty;
                    try
                    {
                        responseXml = XmlUtility.SerializeToString(response.Item.SellingStatus, false);
                        EbayPromoMarkdownData.InsertPromoMarkdownApiLog(apiName, promoSaleId, itemId, requestXml, responseXml, _EbayStatConn);
                    }
                    catch (Exception ex)
                    {
                        //Log Error
                        string errMsg = "LogReqtAndRespError: " + ex.Message;
                        errMsg += "\r\nItemId: " + itemId;
                        errMsg = TextUtility.SubStringIf(errMsg, 4000);
                        EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, string.Empty, errMsg, _EbayStatConn);
                    }
                }
                #endregion
                if (response.Item.SellingStatus.PromotionalSaleDetails != null)
                {
                    if (response.Item.SellingStatus.PromotionalSaleDetails.StartTime.AddMinutes(minuteBuffer) >= promoStartDate)
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        public List<EbayCategoryType> GetCategories(int siteId)
        {
            string apiName = "GetCategories";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            List<EbayCategoryType> cateList = new List<EbayCategoryType>();

            GetCategoriesRequestType request = new GetCategoriesRequestType();
            request.DetailLevel = new DetailLevelCodeType[] { DetailLevelCodeType.ReturnAll };
            request.Version = _Credentials.Version.ToString();
            request.CategorySiteID = siteId.ToString();
            GetCategoriesResponseType response;

            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetCategories(request);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorGeneral("GetCategories", EbayErrorTypeEnum.SysLevel,
                    EbayErrorStatusEnum.Failure, "-1", ex.Message, _EbayStatConn);
                return null;
            }

            if (response != null && response.Errors != null)
            {
                int errCode = 0;
                foreach (ErrorType errType in response.Errors)
                {
                    errCode = 0;
                    errCode = ConvertUtility.ToInt(errType.ErrorCode);
                    EbayErrorData.InsertErrorGeneral("GetCategories", EbayErrorTypeEnum.ApiLevel,
                        EbayErrorStatusEnum.Failure, errCode.ToString(), errType.ShortMessage, _EbayStatConn);
                }
                return null;
            }

            if (response != null && response.CategoryArray != null)
            {
                foreach (CategoryType cat in response.CategoryArray)
                {
                    EbayCategoryType eBayCate = new EbayCategoryType();
                    eBayCate.SiteId = siteId;
                    eBayCate.CategoryId = ConvertUtility.ToInt(cat.CategoryID);
                    eBayCate.CategoryLevel = cat.CategoryLevel;
                    eBayCate.CategoryName = cat.CategoryName;
                    if (cat.CategoryParentID != null && cat.CategoryParentID.Length > 0)
                    {
                        eBayCate.CategoryParentId = ConvertUtility.ToInt(cat.CategoryParentID[0]);
                    }
                    eBayCate.Expired = cat.Expired;
                    eBayCate.LeafCategory = cat.LeafCategory;
                    eBayCate.EbayLastUpdate = response.UpdateTime;
                    cateList.Add(eBayCate);
                }
            }
            return cateList;
        }

        public EbaySellerInfoType GetSellerInfo(int sellerId, string sellerName)
        {
            string apiName = "GetUser";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetUserRequestType getUserRequest = new GetUserRequestType();
            getUserRequest.DetailLevel = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnSummary };
            getUserRequest.UserID = sellerName;
            getUserRequest.Version = _Credentials.Version.ToString();

            EbaySellerInfoType sellerInfo = new EbaySellerInfoType();
            sellerInfo.SellerId = sellerId;
            sellerInfo.EbaySellerName = sellerName;

            GetUserResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetUser(getUserRequest);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.Failure, "-1", ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                return null;
            }

            if (response == null)
            {
                return null;
            }

            if (response.Errors != null)
            {
                EbayErrorStatusEnum errorStatus = EbayErrorStatusEnum.None;
                if (response.Ack == AckCodeType.Warning)
                {
                    errorStatus = EbayErrorStatusEnum.Warning;
                }
                else if (response.Ack == AckCodeType.Failure)
                {
                    errorStatus = EbayErrorStatusEnum.Failure;
                }
                foreach (ErrorType errType in response.Errors)
                {
                    string errMsg = string.Empty;
                    if (errType.SeverityCodeSpecified)
                    {
                        errMsg += errType.SeverityCode.ToString() + ": ";
                    }
                    errMsg += errType.LongMessage;
                    EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.ApiLevel, errorStatus, errType.ErrorCode, errMsg, _EbayStatConn);
                }
            }

            //================
            //PROCESS RESPONSE
            //================
            if (response.User == null)
            {
                //response.Item should be Always return
                EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, "-1", "response.User is null.", _EbayStatConn);
                return null;
            }
            sellerInfo.IsTopRatedSeller = response.User.SellerInfo.TopRatedSeller;

            return sellerInfo;
        }

        public EbaySellerInfoType GetSellerInfo(long itemId, int sellerId, string sellerName)
        {
            string apiName = "GetItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetItemRequestType getitemRequest = new GetItemRequestType();

            getitemRequest.DetailLevel = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnSummary };
            getitemRequest.ItemID = ConvertUtility.Trim(itemId);

            getitemRequest.Version = _Credentials.Version.ToString();

            EbaySellerInfoType sellerInfo = new EbaySellerInfoType();
            sellerInfo.SellerId = sellerId;
            sellerInfo.EbaySellerName = sellerName;

            GetItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetItem(getitemRequest);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.Failure, "-1", ex.Message, _EbayStatConn);

                //Sleep
                System.Threading.Thread.Sleep(_RetrySleepTime);//5000
                //Break  
                return null;
            }
            if (response == null)
            {
                return null;
            }
            if (response.Errors != null)
            {
                foreach (ErrorType errType in response.Errors)
                {
                    if (errType.ErrorCode == "17")
                    {
                        //Item is invalid, not activated, or no longer in our database, or an Live Auction item.
                        return null;
                    }
                    else
                    {
                        EbayErrorData.InsertErrorGetItemLost(itemId, EbayErrorTypeEnum.ApiLevel, errType.LongMessage, _EbayStatConn);
                    }
                }
                return null;
            }

            //================
            //PROCESS RESPONSE
            //================
            if (response.Item == null)
            {
                //response.Item should be Always return
                EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, "-1", "response.Item is null.", _EbayStatConn);
                return null;
            }
            if (response.Item.Seller == null || response.Item.Seller.SellerInfo == null)
            {
                //response.Item.Seller should be Always return
                EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.None, "-1", "response.Item.Seller is null.", _EbayStatConn);
                return null;
            }
            if (response.Item.Seller.SellerInfo.TopRatedSellerSpecified)
            {
                sellerInfo.IsTopRatedSeller = response.Item.Seller.SellerInfo.TopRatedSeller;
            }
            return sellerInfo;
        }

        //Add By Joseph 2010-11-2
        public int GetProductLineId(long itemId)
        {
            string apiName = "GetItem";
            // Create the service 
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);

            GetItemRequestType getitemRequest = new GetItemRequestType();
            getitemRequest.ItemID = ConvertUtility.Trim(itemId);
            getitemRequest.Version = _Credentials.Version.ToString();

            GetItemResponseType response;
            try
            {
                //Must have a count update before anycall
                UpdateSessionCallCount(apiName, ref service);
                response = service.GetItem(getitemRequest);
            }
            catch (Exception ex)
            {
                //=========================
                //RESPONSE ERROR (SYS LEVEL)
                //=========================
                EbayErrorData.InsertErrorGeneral(apiName, EbayErrorTypeEnum.SysLevel, EbayErrorStatusEnum.Failure, "-1", ex.Message, _EbayStatConn);

                throw new Exception(ex.Message);
            }

            int productLineId = 0;
            if (response != null && response.Item != null && response.Item.PictureDetails != null)
            {
                string plPattern = @"\?[\s\S]*pl=(\d+)";
                string imageUrl = response.Item.PictureDetails.GalleryURL;
                if (!string.IsNullOrEmpty(imageUrl) && Regex.IsMatch(imageUrl, plPattern))
                {
                    productLineId = ConvertUtility.ToInt(Regex.Match(imageUrl, plPattern).Groups[1].Value);
                }
                else
                {
                    string[] pictureUrls = response.Item.PictureDetails.ExternalPictureURL;
                    if (pictureUrls != null && pictureUrls.Length > 0)
                    {
                        foreach (string pictureUrl in pictureUrls)
                        {
                            if (!string.IsNullOrEmpty(pictureUrl) && Regex.IsMatch(pictureUrl, plPattern))
                            {
                                productLineId = ConvertUtility.ToInt(Regex.Match(pictureUrl, plPattern).Groups[1].Value);
                                break;
                            }
                        }
                    }
                }
            }
            return productLineId;
        }

        #endregion

        #region Add Nike 2011-03-24 GetOrders
        public void GetOrders(string  sellerId, DateTime startTimeFrom, DateTime startTimeTo,ConnectionStringSettings conn)
        {

            string apiName = "GetOrders";
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            GetOrdersRequestType request = new GetOrdersRequestType();
            //List<GetOrdersArrayType> ordersArray = new List<GetOrdersArrayType>();

            request.Version = _Credentials.Version.ToString();
            request.CreateTimeFromSpecified = true;
            request.CreateTimeFrom = startTimeFrom;
            request.CreateTimeToSpecified = true;
            request.CreateTimeTo = startTimeTo;

            request.DetailLevel = new DetailLevelCodeType[1] {DetailLevelCodeType.ReturnAll };

            //request.IncludeFinalValueFees = true;
            //request.IncludeFinalValueFeesSpecified = true;


            request.OrderRoleSpecified = true;
            request.OrderRole = TradingRoleCodeType.Seller;

            request.OrderStatusSpecified = true;
            request.OrderStatus = OrderStatusCodeType.Completed;
            //request.NumberOfDaysSpecified = true;
            //request.NumberOfDays = 30;

            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.PageNumberSpecified = true;
            request.Pagination.EntriesPerPage = 100;
                try
                {
                    request.Pagination.PageNumber = 1;
                    GetOrdersResponseType response;
                    UpdateSessionCallCount(apiName, ref service);
                    response = service.GetOrders(request);

                    if (response.Errors != null)
                    {
                        foreach (ErrorType errType in response.Errors)
                        {
                            string Msg = errType.ErrorCode + errType.ShortMessage;
                        }
                    }
                    else
                    {
                        if (response.Ack == AckCodeType.Success)
                        {
                            if (response.OrderArray.Length != 0)
                            {
                                GetOrdersArrayType orderItems = new GetOrdersArrayType();
                               
                                    foreach (OrderType orderType in response.OrderArray)
                                    {
                                        orderItems.BuyerUserID = orderType.BuyerUserID;
                                        orderItems.CreateTime = ConvertUtility.ToDateTime(orderType.CreatedTime);
                                        foreach (TransactionType transaction in orderType.TransactionArray)
                                        {
                                            orderItems.BuyerUserEmail = ConvertUtility.Trim(transaction.Buyer.Email);
                                            orderItems.ItemNumber = ConvertUtility.Trim(transaction.Item.ItemID);
                                            orderItems.SKU = ConvertUtility.Trim(transaction.Item.SKU);
                                            orderItems.Quantity = ConvertUtility.ToInt(transaction.Item.Quantity);
                                            orderItems.SalePrice = ConvertUtility.ToDecimal(transaction.ShippingDetails.SalesTax);
                                            orderItems.PayPayTxId = ConvertUtility.Trim(transaction.PaisaPayID);
                                            orderItems.TransactionID = ConvertUtility.Trim(transaction.TransactionID);

                                            StringBuilder strSql = new StringBuilder();
                                            strSql.AppendLine("insert into EbayApiGetOrdersData (EbayUserid,EbayUserEmail,ItemNumber,Sku,Quantity,SalePrice,PayPayTxId,TransactionID,CreateDate) ");
                                            strSql.AppendFormat("values('{0}','{1}','{2}','{3}',{4},", orderItems.BuyerUserID, orderItems.BuyerUserEmail, orderItems.ItemNumber, orderItems.SKU, orderItems.Quantity);
                                            strSql.AppendFormat(" {0},'{1}','{2}','{3}')", orderItems.SalePrice, orderItems.PayPayTxId, orderItems.TransactionID, orderItems.CreateTime);
                                            try
                                            {
                                                DbUtility.ExecuteNonQuery(strSql.ToString(),conn);
                                            }
                                            catch (Exception ex)
                                            {
                                            }
                                        }

                                        //decimal Subtotal = ConvertUtility.ToDecimal(orderType.Subtotal);
                                        //int salesRecordNumber = orderType.ShippingDetails.SellingManagerSalesRecordNumber;

                                    }
                                }

                            
                        }
                        else
                        {

                            string Msg = "No";
                        }

                    }
                }
                catch (Exception ex)
                {
                    
                }


        }
        #endregion


        public void GetSellerTransactionsInfo( int hourProcessLot, int entriesPerPage, int sleepTime, ConnectionStringSettings shippinglabel_Conn)
        {
            string apiName = "GetSellerTransactions";
            eBayAPIInterfaceService service = SetRequesterCredentials(apiName);
            GetSellerTransactionsRequestType request = new GetSellerTransactionsRequestType();
            request.Version = _Credentials.Version.ToString();
            DetailLevelCodeType[] dvt = new DetailLevelCodeType[1] { DetailLevelCodeType.ReturnAll };
            request.DetailLevel = dvt;
            request.Pagination = new PaginationType();
            request.Pagination.EntriesPerPageSpecified = true;
            request.Pagination.EntriesPerPage = entriesPerPage;
            request.Pagination.PageNumberSpecified = true;

            DateTime dateTimeFrom = GetLastProcStartDate(_Credentials.SellerId, shippinglabel_Conn);
            dateTimeFrom = dateTimeFrom.AddHours(-hourProcessLot);//warp time
            DateTime dateTimeTo = dateTimeFrom.AddHours(hourProcessLot);

            while (dateTimeTo < DateTime.Now.ToUniversalTime())
            {
                request.ModTimeFrom = dateTimeFrom;
                request.ModTimeFromSpecified = true;
                request.ModTimeTo = dateTimeTo;
                request.ModTimeToSpecified = true;

                GetSellerTransactionsResponseType response = null;

                int initTotalEntries = 0;
                int initTotalPage = 0;
                int currentTotalEntries = 0;
                int currentTotalPage = 0;
                int currentPageNumber = 1;
                bool finished = false;

              
                #region do----while
                do
                {
                  
                    try
                    {
                        request.Pagination.PageNumber = currentPageNumber;
                        UpdateSessionCallCount(apiName, ref service);

                        response = service.GetSellerTransactions(request);

                        if (response == null)
                        {
                            System.Threading.Thread.Sleep(sleepTime);
                            finished = true;
                            continue;
                            
                        }

                        if (response.Errors != null)
                        {
                            #region Error
                            foreach (ErrorType err in response.Errors)
                            {
                                string errMsg = err.LongMessage;
                                if (err.ErrorCode == "340")
                                {
                                    //Page number is out of range.
                                    errMsg += "CurrentPage:" + currentPageNumber
                                        + " LastTotalPage:" + currentTotalPage + " LastTotalEntries:" + currentTotalEntries
                                        + " InitTotalPage:" + initTotalPage + " InitTotalEntries:" + initTotalEntries;
                                    //By Pass
                                    finished = true;
                                }

                                InsertErrorGetSellerTransactions(_Credentials.SellerId, dateTimeFrom, dateTimeTo, entriesPerPage, currentPageNumber, EbayErrorTypeEnum.ApiLevel, Convert.ToInt32(err.ErrorCode), errMsg, shippinglabel_Conn);
                            }
                            System.Threading.Thread.Sleep(sleepTime);
                            #endregion
                        }
                        else
                        {
                            #region Get EbayUser Information  Success

                            if (response.Ack == AckCodeType.Success)
                            {
                                if (currentPageNumber == 1)
                                {
                                    initTotalPage = response.PaginationResult.TotalNumberOfPages;
                                    initTotalEntries = response.PaginationResult.TotalNumberOfEntries;
                                }
                                currentTotalPage = response.PaginationResult.TotalNumberOfPages;
                                currentTotalEntries = response.PaginationResult.TotalNumberOfEntries;

                                if (response.TransactionArray != null)
                                {
                                    GetOrdersArrayType orderItems = new GetOrdersArrayType();
                                    foreach (TransactionType transaction in response.TransactionArray)
                                    {
                                        if (transaction.Status.CheckoutStatus == CheckoutStatusCodeType.CheckoutComplete)
                                        {
                                            #region  Insert Data To Table
                                            try
                                            {
                                                orderItems.SellerId = _Credentials.SellerId;
                                                orderItems.BuyerUserID = ConvertUtility.Trim(transaction.Buyer.UserID);
                                                orderItems.BuyerUserEmail = ConvertUtility.Trim(transaction.Buyer.Email);
                                                orderItems.ItemNumber = ConvertUtility.Trim(transaction.Item.ItemID);

                                                //2013-2-19 fong
                                                if (transaction.Item.SKU != null)
                                                {
                                                    orderItems.SKU = GetSku(ConvertUtility.Trim(transaction.Item.SKU));
                                                }
                                                else
                                                {
                                                    if (transaction.Variation != null)
                                                    {
                                                        orderItems.SKU = GetSku(ConvertUtility.Trim(transaction.Variation.SKU));
                                                    }
                                                    else
                                                    {
                                                        orderItems.SKU = GetSku(ConvertUtility.Trim(transaction.Item.ItemID));//fong test 000
                                                    }

                                                }
                                                ////////////////////////
                                                 
                                                orderItems.Quantity = ConvertUtility.ToInt(transaction.QuantityPurchased);
                                                orderItems.SalePrice = ConvertUtility.ToDecimal(transaction.TransactionPrice.Value);
                                                
                                                orderItems.TransactionID = ConvertUtility.Trim(transaction.TransactionID);
                                                orderItems.CreateTime = ConvertUtility.ToDateTime(transaction.CreatedDate);
                                                orderItems.PayTime = ConvertUtility.ToDateTime(transaction.CreatedDate);
                                                //add by Fong 2012-7-31
                                                orderItems.EbayOrderNumber = ConvertUtility.ToInt(transaction.ShippingDetails.SellingManagerSalesRecordNumber);
                                                orderItems.PayPayTxId = ConvertUtility.Trim(transaction.ExternalTransaction[0].ExternalTransactionID);
                                                orderItems.ShipName = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.Buyer.BuyerInfo.ShippingAddress.Name));
                                                orderItems.ShipAddress1 = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.Buyer.BuyerInfo.ShippingAddress.Street1));
                                                orderItems.ShipAddress2 = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.Buyer.BuyerInfo.ShippingAddress.Street2));
                                                orderItems.ShipCity = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.Buyer.BuyerInfo.ShippingAddress.CityName));
                                                orderItems.ShipState = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.Buyer.BuyerInfo.ShippingAddress.StateOrProvince));
                                                orderItems.ShipCountry = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.Buyer.BuyerInfo.ShippingAddress.Country));
                                                orderItems.ShipZip = ConvertUtility.Trim(transaction.Buyer.BuyerInfo.ShippingAddress.PostalCode);
                                                orderItems.ShipPhone = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.Buyer.BuyerInfo.ShippingAddress.Phone));
                                                orderItems.ShipMethod = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.ShippingServiceSelected.ShippingService));
                                                orderItems.BuyerCheckoutMessage = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.BuyerCheckoutMessage));
                                                orderItems.Total = ConvertUtility.ToDecimal(transaction.AmountPaid.Value);
                                                //orderItems.Freight = ConvertUtility.ToDecimal(transaction.ActualShippingCost.Value);
                                                orderItems.Title = ReplaceQuotationMarks(ConvertUtility.Trim(transaction.Item.Title));
                                                orderItems.Site = ConvertUtility.Trim(transaction.TransactionSiteID);
                                                orderItems.CurrencyID = ConvertUtility.Trim(transaction.AmountPaid.currencyID);
                                                orderItems.CompleteStaus = ConvertUtility.Trim(transaction.Status.CompleteStatus);
                                                orderItems.eBayPaymentStatus = ConvertUtility.Trim(transaction.Status.eBayPaymentStatus);


                                                InsertTransactionsDatas(orderItems, shippinglabel_Conn);
                                            }
                                            catch (Exception exp)
                                            {
                                                InsertErrorGetSellerTransactions(_Credentials.SellerId, dateTimeFrom, dateTimeTo, -1, -1, EbayErrorTypeEnum.SysLevel, -1, exp.Message, shippinglabel_Conn);
                                                continue;
                                            }

                                            #endregion
                                        }

                                    }

                                }

                                #region Next Page
                                if (currentPageNumber >= response.PaginationResult.TotalNumberOfPages)
                                {
                                    finished = true;
                                }
                                else
                                {
                                    currentPageNumber++;
                                }

                                #endregion
                            }

                            #endregion
                        }

                    }
                    catch (Exception ex)
                    { 
                        InsertErrorGetSellerTransactions(_Credentials.SellerId, dateTimeFrom, dateTimeTo, -1, -1, EbayErrorTypeEnum.SysLevel, -1, ex.Message, shippinglabel_Conn);
                        finished = true;
                    } 

                } while (!finished);
                InsertProcHistSellerTransactions(_Credentials.SellerId, dateTimeTo, shippinglabel_Conn);
                dateTimeFrom = dateTimeTo;
                dateTimeTo = dateTimeFrom.AddHours(hourProcessLot);

                #endregion;
            }

        }

        #region SellerTransaction DataBase add Nike 2011-3-26
        /// <summary>
        /// add Nike 2011-3-26
        /// </summary>
        /// <param name="orders"></param>
        /// <param name="Conn"></param>
        private void InsertTransactionsDatas(GetOrdersArrayType orders, ConnectionStringSettings Conn)
        {
            string funMsg = "InsertTransactionsDatas(GetOrdersArrayType orders, ConnectionStringSettings conn)";

            StringBuilder strSql = new StringBuilder();
            strSql.AppendLine(" if not exists( select 1 from SellerTransactions ");
            strSql.AppendFormat(" where ebayuserid='{0}' and sellerid={1} and transactionid='{2}' and eBayPaymentStatus = '{3}' and EbayOrderNumber = {4} and PaypalTxID = '{5}')", orders.BuyerUserID, orders.SellerId, orders.TransactionID, orders.eBayPaymentStatus, orders.EbayOrderNumber, orders.PayPayTxId);//fong 2013-5-24 add EbayOrderNumber and PayPayTxId
            strSql.AppendLine(" begin ");
            strSql.AppendLine("insert into dbo.SellerTransactions (EbayUserid,EbayUserEmail,ItemNumber,Sku,Quantity,SalePrice,PaypalTxID,TransactionID,CreateDate,SellerId,PayTime, EbayOrderNumber,ShipName,ShipAddress1,ShipAddress2,ShipCity,ShipState,ShipCountry,ShipZip,ShipPhone,PaymentMethod,Total,Freight,Title,BuyerCheckoutMessage,ShipMethod,Site,CurrencyID,CompleteStatus,eBayPaymentStatus) ");
            strSql.AppendFormat("values('{0}','{1}','{2}','{3}',{4},", orders.BuyerUserID, orders.BuyerUserEmail, orders.ItemNumber, orders.SKU, orders.Quantity);
            strSql.AppendFormat(" {0},'{1}','{2}','{3}',", orders.SalePrice, orders.PayPayTxId, orders.TransactionID, orders.CreateTime);
            strSql.AppendFormat(" '{0}','{1}',", orders.SellerId, orders.PayTime);
            strSql.AppendFormat(" '{0}',N'{1}',N'{2}',N'{3}',N'{4}',", orders.EbayOrderNumber, orders.ShipName, orders.ShipAddress1, orders.ShipAddress2,orders.ShipCity);
            strSql.AppendFormat(" N'{0}',N'{1}',N'{2}',N'{3}',N'{4}',", orders.ShipState, orders.ShipCountry, orders.ShipZip,orders.ShipPhone,orders.PaymentMethod);
            strSql.AppendFormat(" {0},{1},",orders.Total, orders.Freight);
            strSql.AppendFormat(" '{0}',N'{1}',N'{2}',N'{3}',N'{4}',N'{5}',N'{6}')", orders.Title, orders.BuyerCheckoutMessage, orders.ShipMethod, orders.Site, orders.CurrencyID, orders.CompleteStaus,orders.eBayPaymentStatus);
            strSql.AppendLine(" end ");
            try
            {
                DbUtility.ExecuteNonQuery(strSql.ToString(), Conn);
            }
            catch (Exception ex)
            {
                string exMsg = "Exception:" + ex.ToString() + FileUtility.NewLine + "Sql:" + strSql.ToString() + FileUtility.NewLine + funMsg;
                throw new Exception(exMsg, ex);
            }

        }

        private  int InsertErrorGetSellerTransactions(int sellerId, DateTime startUTCTime, DateTime endUTCTime, int entriesPerPage, int pageNumber, EbayErrorTypeEnum errorType, int errorCode, string errMsg, ConnectionStringSettings Conn)
        {
            string funMsg = "static int InsertErrorGetSellerTransactions(int sellerId, DateTime startUTCTime, DateTime endUTCTime, int entriesPerPage, int pageNumber, EbayErrorTypeEnum errorType, int errorCode, string errMsg, ConnectionStringSettings Conn)";
            StringBuilder sbSql = new StringBuilder();
            try
            {
                sbSql.Append(" Insert into ErrorGetSellerTransactions(SellerId,StartUTCTime,EndUTCTime,");
                if (entriesPerPage > 0)
                {
                    sbSql.Append(" EntriesPerPage,");
                }
                if (pageNumber > 0)
                {
                    sbSql.Append(" PageNumber ,");
                }
                sbSql.Append(" ErrorType ,ErrorCode,ErrorMsg,ComputerName,LastUpdate ) Values (");
                sbSql.AppendFormat("{0},'{1}','{2}',", sellerId, startUTCTime.ToString(), endUTCTime.ToString());
                if (entriesPerPage > 0)
                {
                    sbSql.AppendFormat("{0},", entriesPerPage);
                }
                if (pageNumber > 0)
                {
                    sbSql.AppendFormat("{0},", pageNumber);
                }
                sbSql.AppendFormat("{0},{1},N'{2}',N'{3}',getdate() )", (int)errorType, errorCode, DbUtility.ParseSql(errMsg), SystemUtility.MachineName);

                return DbUtility.ExecuteNonQuery(sbSql.ToString(), Conn);
            }
            catch (Exception ex)
            {
                string exMsg = "Exception:" + ex.ToString() + FileUtility.NewLine + "Sql:" + sbSql.ToString() + FileUtility.NewLine + funMsg;
                throw new Exception(exMsg, ex);
            }
        }

        private  int InsertProcHistSellerTransactions(int sellerId, DateTime processDateTimeUTC, ConnectionStringSettings Conn)
        {
            string funMsg = "private  int InsertProcHistSellerTransactions(int sellerId, DateTime processDateTimeUTC, ConnectionStringSettings Conn)";
            StringBuilder sbSql = new StringBuilder();
            try
            {
                sbSql.AppendFormat(" IF NOT EXISTS("
                    + " SELECT 1 FROM ProcHistSellerTransactions (nolock) WHERE SellerId={0} )"
                    + " INSERT ProcHistSellerTransactions( [SellerId],[ProcStartDate],[ComputerName],[LastUpdate] )"
                    + " VALUES ( {0},'{1}','{2}',getdate() )"
                    + " ELSE"
                    + " UPDATE ProcHistSellerTransactions"
                    + " SET ProcStartDate='{1}', ComputerName='{2}',"
                    + " LastUpdate=getdate() WHERE SellerId={0}"
                    , sellerId, processDateTimeUTC, DbUtility.ParseSql(SystemUtility.MachineName));
                return DbUtility.ExecuteNonQuery(sbSql.ToString(), Conn);
            }
            catch (Exception ex)
            {
                string exMsg = "Exception:" + ex.ToString() + FileUtility.NewLine + "Sql:" + sbSql.ToString() + FileUtility.NewLine + funMsg;
                throw new Exception(exMsg, ex);
            }
        }

        private  DateTime GetLastProcStartDate(int sellerId, ConnectionStringSettings Conn)
        {
            string funMsg = "private  DateTime GetLastProcStartDate(int sellerId, ConnectionStringSettings Conn)";
            StringBuilder sbSql = new StringBuilder();
            try
            {
                sbSql.AppendFormat(" SELECT ProcStartDate FROM ProcHistSellerTransactions (nolock)"
                    + " WHERE SellerId = {0}", sellerId);
                DateTime dt = ConvertUtility.ToDateTime(DbUtility.ExecuteScalar(sbSql.ToString(), Conn));
                if (dt == DateTime.MinValue)
                {
                    dt = DateTime.Now.ToUniversalTime().AddDays(-2);
                }
                return dt;
            }
            catch (Exception ex)
            {
                string exMsg = "Exception:" + ex.ToString() + FileUtility.NewLine + "Sql:" + sbSql.ToString() + FileUtility.NewLine + funMsg;
                throw new Exception(exMsg, ex);
            }
        }


        /// <summary>
        /// get Sku Split '_'
        /// </summary>
        /// <param name="strSku"></param>
        /// <returns></returns>
        private string GetSku(string strSku)
        {
            string[] Sku = System.Text.RegularExpressions.Regex.Split(strSku, @"_");
            return ConvertUtility.Trim(Sku[0].ToString());
        }

        private string ReplaceQuotationMarks(string str_QM)
        {
            string str = str_QM;
            str = str.Replace("'","''");
            return str;
        } 

        #endregion



    }//end class
}//end namespace
